简体   繁体   中英

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. I mean I want to get Jonathan's and Samantha's objects in another list. How can I do that? Thanks.

With Join for example

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 .

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>> result = list1.Concat(list2)
    .GroupBy(x => x.ID)
    .ToDictionary(g => g.Key, g => g.ToList());

You can do this with a 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM