Use of Predicate delegate in Find() method of generic List<>

Using the generic List clollection might create a problem with the List.Contains() method.If a condition is placed to check if the generic List contains some string then it returns 'true' only if the string which is passed to "Contains()" method is in in same case as stored in the list.
For example, if List contains a string value "TEST" and we call the List.Contains("Test") then it returns "false" as it treats "name" and "Name" different values even they are same.
To overcome this problem, we can use "Find()" method of a generic List and pass a delegate which will compare the case sensitiveness of string values.


using System.Collections.Generic;
class TestList
{
public void CheckValueInList(List stringList)
{
if(stringList != null)
{
string result = stringList.Find(new Predicate(IsEqualString);
}
}

public static bool IsEqualString(string name)
{
return (name.Equals("NAME",
StringComparison.OrdinalIgnoreCase));
}


}


By using the Predicate delegate with the generic List we get the return value as "True" as delegte invokes the associated method to check string comparison.In this way, we can overcome the limitation of "Contains()" method.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: