Comparing strings in 2 list using Linq

15,275

Solution 1

You mean you want items in listB where it contains any of the elements in listA?

listB.Where(b => listA.Any(a => b.Contains(a))

Solution 2

You can do it in LINQ:

listB.Where(e => listA.Any(a => e.Contains(a)));

Bear in mind that this algorithm has a runtime cost similar to O(n^2), it will therefore slow down quickly as the number of elements in your lists grows.

Solution 3

You can also implement things like that :

  public class EqualityComparer : IEqualityComparer<string>
  {

    public bool Equals(string x, string y)
    {
      return y.Contains(x);
    }

    public int GetHashCode(string obj)
    {
      return 1;
    }
   }

and then use intersect like that:

 listB.Intersect(listA, new EqualityComparer()).ToList();
Share:
15,275
user2590683
Author by

user2590683

Updated on June 08, 2022

Comments

  • user2590683
    user2590683 almost 2 years

    I need to compare to list with strings, and find whitch elements that are similar. ie.

    List<string> listA = {"ProfileHeight", "ProfileWidth", "WebThickness"}
    List<string> listB ={"ProfileHeightVisibility", "ProfileWidthVisibility", "WebThicknessVisibility", "FlangeThicknessVisibility", "DepthVisibility"}
    

    I was wondering if it is possible to use Linq. I want the result to be a list with the elements from ListB that have a name similar to the strings in listA. Where the statemant i.e. "ProfileHeightVisibility.Contains("ProfileHeight") = true

  • Matthias Meid
    Matthias Meid almost 11 years
    Why do you use string.Compare? This method returns an integer stating the lexical order of two strings rather than a boolean, does it not?
  • toszo
    toszo almost 11 years
    Yeah, good point. I corrected my answer. Comparing strings by "==" could cause problems with culture, encoding or case sensitiveness of words. This example shows how to handle those things.
  • Matthias Meid
    Matthias Meid almost 11 years
    I'm not sure whether the strings are supposed to be equal. However, I'd maybe rather use string.Equals(a, b, StringComparision.InvariantCultureIgnoreCase) msdn.microsoft.com/en-us/library/t4411bks.aspx
  • toszo
    toszo almost 11 years
    You are right, it could be even better to use String.Equals.