Jason Towne
Jason Towne

Reputation: 8050

Return a list where items in list 1 and list 2 match

Let's assume I have 2 List<T> List1 and List2 that look like this:

List 1:

[ID:1, Name:"item1"]
[ID:2, Name:"item2"]
[ID:3, Name:"item3"]
[ID:4, Name:"item4"]

List 2:

[ID:2, Name:"item2"]
[ID:3, Name:"item3"]
[ID:5, Name:"item5"]
[ID:6, Name:"item6"]

How can I get a list that contains only the objects that are in both lists? Using the example above, I want to return:

[ID:2, Name:"item2"]
[ID:3, Name:"item3"]

Modifying the original lists is OK. What's the best way to do this?

Upvotes: 1

Views: 7327

Answers (4)

Matt Greer
Matt Greer

Reputation: 62027

  var result = list1.Intersect(list2).ToList();

Is the most succinct. However keep in mind it is using the default equality comparer which may or may not work for you. If not, you can provide your own:

    public class MyEqualityComparer : IEqualityComparer<Foo>
    {
        public bool Equals(Foo x, Foo y)
        {
            return x.Id == y.Id;
        }

        public int GetHashCode(Foo obj)
        {
            return obj.Id.GetHashCode();
        }
    }

  var result = list1.Intersect(list2, new MyEqualityComparer()).ToList();

Upvotes: 6

BrokenGlass
BrokenGlass

Reputation: 160852

If there are no duplicates in the list you can do this:

var combinedList = list2.Intersect(list1).ToList();

Edit:

As @Matt Greer pointed out you will need a custom equality comparer for this to work as you would expect.

Upvotes: 4

Freesn&#246;w
Freesn&#246;w

Reputation: 32133

Using lua code here:

ArrayList1={}
ArrayList2={}

function inTable(tbl,val)
   for _,v in ipairs(tbl) do
      if v==val then return true end
   end
   return false
end

function getSame(tbl1,tbl2)
   returnArray={}
   for _,v in ipairs(tbl1) do
      if inTable(tbl2,v) then table.insert(returnArray,v) end
   end
end

newArray=getSame(arrayList1,arrayList2)

I'm not too familiar with C#.

Upvotes: -1

Tejs
Tejs

Reputation: 41236

Like jQuery, the answer is always LINQ!

var intersection = list1.Where(item => list2.Contains(item)).ToList();

Assuming the list contains a copy of the actual reference. If not, then do:

var intersection = list1.Where(item => list2.Count(match => item.ID == match.ID && item.Name == match.Name) > 0).ToList();

Upvotes: 1

Related Questions