Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq join 1 to many get first record

Tags:

linq

I have 2 list:

List1:

ID
1
2
3

List2:

ID   Name
1  Jason
1  Jim
2  Mike
3  Phil

I like to join both of these but get only the first record from list2 for a given ID: The end result would be

ID Name
1  Jason
2  Mike
3  Phil

I tried the following but was not successful:

    var lst = (from lst1 in list1
               join lst2 in list2
               on lst1.ID equals lst2.ID).ToList().First();          
like image 537
Nate Pet Avatar asked Jan 18 '23 15:01

Nate Pet


2 Answers

You can get this result with what the 101 LINQ Samples calls "Cross Join with Group Join". Combine that with First() to get just one item from the group.

var lst = (
    from lst1 in list1
    join lst2 in list2 on lst1.ID equals lst2.ID into lstGroup
    select lstGroup.First()
);

Example: http://ideone.com/V0sRO

like image 116
Tommy Vernieri Avatar answered Feb 09 '23 00:02

Tommy Vernieri


Try grouping list2 by ID first and then selecting the first item from each group. After that, do the join and select what you want.

var uniqueIDList2 = list2.GroupBy(p => p.ID)
                         .Select(p => p.First());

var result = from lst1 in list1
             join lst2 in uniqueIDList2 on lst1.ID equals lst2.ID
             select new { lst1.ID, lst2.Name };
like image 38
Adam S Avatar answered Feb 09 '23 00:02

Adam S