Linq join 1 to many get the first record

I have 2 lists:

List1:

ID 1 2 3

List2:

Identification name

1 Jason 1 Jim 2 Mike 3 Phil

I like to join both of them, but get only the first entry from list2 for a given ID: The end result will be

ID 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(); 
+4
source share
4 answers

You can get this result with 101 LINQ Samples calling "Cross Join with Group Join" . Combine this with First() to get only 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

+6
source

Here is one way to do this:

 var lst = list1 // Select distinct IDs that are in both lists: .Where(lst1 => list2 .Select(lst2 => lst2.ID) .Contains(lst1.ID)) .Distinct() // Select items in list 2 matching the IDs above: .Select(lst1 => list2 .Where(lst2 => lst2.ID == lst1.ID) .First()); 

Example: http://ideone.com/6egSc

+2
source

First try to group list2 by ID, and then select the first item from each group. After that, make a connection 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 }; 
+1
source

Another way:

 var query = from lst1 in list1 let first = list2.FirstOrDefault(f => f.Id == lst1.Id) where first != null select first; 

Or, if you want to know about elements that could not be located in list2:

 var query = from lst1 in list1 let first = list2.FirstOrDefault(f => f.Id == lst1.Id) select first ?? new { Id = 0, Name = "Not Found" }; 
0
source

Source: https://habr.com/ru/post/1394088/


All Articles