Click here to Skip to main content
15,905,914 members
Articles / Programming Languages / C#
Tip/Trick

Filtering Generic C# List

Rate me:
Please Sign up or sign in to vote.
4.60/5 (3 votes)
26 Aug 2013CPOL 31.1K   302   6  
Filetring generic C# List using using customer method

Introduction

List can be filtered using various methods like Linq Where or using List.Contains method but there are situations where you need some custom logic while filtering.

Background

Mostly while filtering List, you can simply use Linq Where or string.Contains method, e.g., if you have a string "My name is Khan" and you want to compare that with "My name" or "is Khan" so string.Contains would be the simplest way to go through but what if you require to compare each word regardless of their sequence like if you have to compare "My name is Khan" with "Khan name" in this case string.Contains would return false.

Using the Code

C#
public static bool SqlLike(string strMain, string strSub)
{
    string[] subStrings = strSub.Split(' ');

    foreach (string subString in subStrings)
    {
        if (strMain.Contains(subString) == false)
        {
            return false;
        }
    }
    return true;
}

private bool FilterBarFun(Item value)
{
    return SqlLike(value.ItemName.ToUpper(),txtFilterString.Text. ToUpper());                 
}

private void txtFilterString_TextChanged(object sender, EventArgs e)
{
    subItems = items.FindAll(FilterBarFun);

    if (txtFilterString.Text.Length > 0)
    {
        source.DataSource = subItems;
    }
    else
    {
        source.DataSource = items;
    }
}

Points of Interest

This could be useful for filtering items where you have concatenated name like "Product Name" + " " + "Brand" + " " + "Model" + " " + "Size".

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Pakistan Pakistan
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --