linqiequalitycomparerstringcomparer

Linq IEqualityComparer<string> Ignore Case


I am sorting a list of elements:

var matchEle = listOfElements.Where(e => e.Properties().Any(p => p.Name.Contains("Key", Asking for IEqualityComparer))).First();

I am used to just going straight to a StringComparer, OrdinalIgnoreCase or CurrentCultureIgnoreCase, however when calling Contains() in this context, it is asking for an IEqualityComparer. I imagine because of the data structure/level. I saw an example of how to set up an IEqualityComparer such as

strEqualityComparer = new IEqualityComparer();

and defining the class for strEqualityComparer but I am not sure beyond that. Can someone help me get my linq statement to work with an ignore case?

Update: Just so I'm clear here is an example of the data structure:

listOfElements = [element1, element2, etc..]
element1.Properties = ["Prop1", "Key1", "Prop2", "Key2", etc.]

I need to extract the elements which pass the filter if any of its properties has a value containing the keyword, in this case "Key" therefore it cannot be .Equals or IndexOf.


Solution

  • Update as per comment

    Search string inside another string:

    var matchEle = listOfElements
    .Where(e => e.Properties().Any(p => p.Name.IndexOf("Key", System.StringComparison.OrdinalIgnoreCase) >= 0))
    .First();
    

    Old solutions

    You have two options, that depends on Name type:
    1 - Without IEqualityComparer, and if Name in Properties is a string. replace Contains by Equals like :

    var matchEle = listOfElements
        .Where(e => e.Properties().Any(p => p.Name.Equals("Key", StringComparison.OrdinalIgnoreCase)))
        .First();
    

    2 - With IEqualityComparer, and if Name in Properties is a list of string:
    2.1 : Create a custom comparer, like:

    public class StringIEqualityComparer : IEqualityComparer<string>
    {
        public bool Equals(string x, string y)
        {
            return x.Equals(y, StringComparison.OrdinalIgnoreCase);
        }
    
        public int GetHashCode(string obj)
        {
            return obj.GetHashCode();
        }
    }
    

    2.2 : change little your query to :

    var matchEle = listOfElements
    .Where(e => e.Properties().Any(p => p.Name.Contains("Key", new StringIEqualityComparer())))
    .First();
    

    I hope this helps you.