Using predicates for Find / FindAll methods on generic List<T> in C#

The call to FindAll:

myDerivedClass.FindAll(MyBaseClass.AnyWordInNameStartsWith(partialName));

Within MyBaseClass.cs:

 
public static Predicate AnyWordInNameStartsWith(string partialName) where T:MyBaseClass, new()
{
return delegate(T myClass)
{
partialName = partialName.ToLowerInvariant();
 
if (myClass.Name.ToLowerInvariant().StartsWith(partialName))
{
return true;
}
 
List words = new List();
string[] splWords = myClass.Name.ToLowerInvariant().Split(' ');
for (int i = 0; i &lt; splWords.Length; i++)
{
words.Add(splWords[i]);
if (i &gt; 0)
{
StringBuilder restOfName = new StringBuilder();
for (int j = i; j &lt; splWords.Length; j++)
{
restOfName.Append(splWords[j]);
if (j &lt; splWords.Length - 1)
{
restOfName.Append(" ");
}
}
words.Add(restOfName.ToString());
}
}
}
words.Sort();
foreach (string word in words)
{
if (word.StartsWith(partialName))
{
return true;
}
}
return false;
};
}



This entry was posted in C#. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *