3

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

1
  • And by "similar" you mean StartsWith or Contains? Commented Jul 30, 2013 at 8:10

5 Answers 5

20

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))
Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

1

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();

Comments

1
List<string> listA = new List<string> { "zinmin", "zin1", "zin2" };
List<string> listB = new List<string> { "zinmin", "min1", "min2" };



List<string> matching = listA.Intersect(listB).ToList();

matching result will come {"zinmin"} . Sorting order doesn't matter.

Comments

0

Yes you can do such thing with LINQ

    public List<string> GetSimilarStrings(List<string> list1, List<string> list2)
    {
        return (from item in list1 from item2 in list2 where string.Equals(item,item2,StringComparison.InvariantCultureIgnoreCase) select item).ToList();
    }

4 Comments

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?
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.
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
You are right, it could be even better to use String.Equals.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.