MoonKnight
MoonKnight

Reputation: 23831

Getting a List<T> from Matching two Seperate List<T>s

All, I would like to know if there is a better way of getting a List<T> of matching values from two seperate List<T>s.

The way I would do this currently if I wanted to find all the items in string list itemList<string> (a distinct list) that were in another list bankList<string> (also distinct so the returned list is also distinct - no duplicates) would be

List<string> matchingList = new List<string>();
foreach (string s in itemList)
    if (bankList.Contains(s))
        matchingList.Add(s);

Is there a better and/or quicker way of doing this?

Extension: I appreciate the question has been answered (and this is taking advantage) but out of interest, would the best way of getting the negation (that is, those items not in bankList<string>) be

List<string> interList = new List<string>();
interList = itemList.Intersect(bankList).ToList<string>();
matchingList = itemList.Except(interList).ToList<string>();

or in this case would it be back to

List<string> matchingList = new List<string>();
foreach (string s in itemList)
    if (!bankList.Contains(s))
        matchingList.Add(s);

I think in this case it interestingly could be the latter?

Upvotes: 3

Views: 195

Answers (1)

jason
jason

Reputation: 241789

There is a clearer way to do this:

var matchingList = itemList.Intersect(bankList).ToList();

Moreover, it will be faster, because it won't be O(n^2). Right now, you're traversing the bankList for every item in itemList. Instead, you should build a HashSet from itemList, and then check for containment in that HashSet as you walk bankList. That's exactly what Enumerable.Intersect will do.

So, you win on both fronts: performance and readability.

would the best way of getting the negation (that is, those items not in bankList) be

Just say

var except = itemList.Except(bankList).ToList();

Upvotes: 16

Related Questions