[英]Intersection of two lists by a member
I have an object like this : 我有一个这样的对象:
public class myObject
{
public string Name {get; set;}
public string ID {get; set;}
}
I have two lists like this 我有两个这样的清单
List<myObject> list1 = new List<myObject>();
list1.Add(new myObject(){Name = Jason, ID = 1});
list1.Add(new myObject(){Name = Jonathan, ID = 2});
list1.Add(new myObject(){Name = Kevin, ID = 3});
List<myObject> list2 = new List<myObject>();
list2.Add(new myObject(){Name = Jennifer, ID = 5});
list2.Add(new myObject(){Name = Samantha, ID = 2});
list2.Add(new myObject(){Name = Lucy, ID = 9});
I want to intersect these two lists by their ID
s. 我想用ID
将这两个列表相交。 I mean I want to get Jonathan's and Samantha's objects in another list. 我的意思是我想将Jonathan和Samantha的对象列入另一个列表。 How can I do that? 我怎样才能做到这一点? Thanks. 谢谢。
With Join
for example 以Join
为例
var query = from o1 in list1
join o2 in list2 on o1.ID equals o2.ID
select new { Object1 = o1, OBject2 = o2 };
I don't know what kind of list you want as result because your class has only one property ID
. 我不知道您想要什么样的列表,因为您的课程只有一个属性ID
。
Maybe you want a Dictionary<int, List<myObject>>
instead, the dictionary has the common ID as key and a list with the objects as value: 也许您想要使用Dictionary<int, List<myObject>>
代替,该字典将公共ID作为键,并将具有对象的列表作为值:
Dictionary<int, List<myObject>> result = list1.Concat(list2)
.GroupBy(x => x.ID)
.ToDictionary(g => g.Key, g => g.ToList());
You can do this with a Join
您可以通过Join
来做到这一点
var result = list1.Join(list2, l1 => l1.ID, l2 => l2.ID,
(lhs,rhs) => new {ID = lhs.ID, Name1 = lhs.Name, Name2 = rhs.Name};
);
Live example: http://rextester.com/OAJRG62251 实时示例: http : //rextester.com/OAJRG62251
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.