LINQ Join 2 Lists

后端 未结 4 891
感情败类
感情败类 2020-11-29 07:36

Preface: I don\'t understand what this does:

o => o.ID, i => i.ID, (o, id) => o

So go easy on me. :-)


I have 2 lis

4条回答
  •  庸人自扰
    2020-11-29 07:59

    Joins are not so difficult, but your problem could probably use some further explanation.

    To join two lists, you could do something like

    var joined = from Item1 in list1
                 join Item2 in list2
                 on Item1.Id equals Item2.Id // join on some property
                 select new { Item1, Item2 };
    

    this will give an IEnumerable<'a>, where 'a is an anonymous type holding an item from list1 and its related item from list2. You could then choose which objects' properties to use as needed.

    To get the result to a concrete list, all that is needed is a call to .ToList(). You can do that like

    var list3 = joined.ToList();
    // or
    var list3 = (from Item1 in list1
                 join Item2 in list2
                 on Item1.Id equals Item2.Id // join on some property
                 select new { Item1, Item2 }).ToList();
    

    To do a left join to select all elements from list1 even without a match in list2, you can do something like this

    var list3 = (from Item1 in list1
                 join Item2 in list2
                 on Item1.Id equals Item2.Id // join on some property
                 into grouping
                 from Item2 in grouping.DefaultIfEmpty()
                 select new { Item1, Item2 }).ToList();
    

    This will give you a list where Item1 equals the item from the first list and Item2 will either equal the matching item from the second list or the default, which will be null for a reference type.

提交回复
热议问题