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"]
Ho开发者_JS百科w 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?
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();
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.
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();
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#.
精彩评论