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();
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
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 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With