In my application with Linq to SQL, the user can search for text. An asterix (*) can be used at the beginning and/or end of the search expression. The code now is this:
var search = SearchTextBox.Text.Trim();
bool filterStartsWith = false, filterEndsWith = false;
if (!string.IsNullOrEmpty(search))
{
filterStartsWith = search.EndsWith("*");
filterEndsWith = search.StartsWith("*");
if (filterStartsWith) search = search.Substring(0, search.Length - 1);
if (filterEndsWith) search = search.Substring(1);
if (filterStartsWith)
{
if (filterEndsWith)
{
query = query.Where(item => item.Omschrijving.Contains(search));
}
else
{
query = query.Where(item => item.Omschrijving.StartsWith(search));
}
}
else
{
if (filterEndsWith)
{
query = query.Where(item => item.Omschrijving.EndsWith(search));
}
else
{
query = query.Where(item => item.Omschrijving == search);
}
}
}
However, I want to generalize this, because this kind of search happens on more places. Also, some tables, this should happen on more than one column. Any ideas?
I use Visual Studio 2010 with .NET Framework 4.0.