fork download
  1. using System;
  2. using System.Linq;
  3.  
  4. public class Test
  5. {
  6. public static void Main()
  7. {
  8. var list1 = new[] { new { ID = 1 }, new { ID = 2 }, new { ID = 3 } };
  9. var list2 = new[] {
  10. new {
  11. ID = 1,
  12. Name = "Jason"
  13. },
  14. new {
  15. ID = 1,
  16. Name = "Jim"
  17. },
  18. new {
  19. ID = 2,
  20. Name = "Mike"
  21. },
  22. new {
  23. ID = 3,
  24. Name = "Phil"
  25. }
  26. };
  27.  
  28. var lst = list1
  29. // Select distinct IDs that are in both lists:
  30. .Where(lst1 => list2
  31. .Select(lst2 => lst2.ID)
  32. .Contains(lst1.ID))
  33. .Distinct()
  34. // select items in list 2 matching the IDs above:
  35. .Select(lst1 => list2
  36. .Where(lst2 => lst2.ID == lst1.ID)
  37. .First());
  38.  
  39. foreach(var item in lst)
  40. {
  41. Console.WriteLine("ID: {0}, Name: {1}", item.ID, item.Name);
  42. }
  43. }
  44. }
Success #stdin #stdout 0.05s 37224KB
stdin
Standard input is empty
stdout
ID: 1, Name: Jason
ID: 2, Name: Mike
ID: 3, Name: Phil