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
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".
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.