Search code examples
c#linq

Merge results from 2 different Lists using identifier


I have 2 different list of objects that have a few thousand entries but for the sake simplicity lets assume they look something like this:

LIST A [
   {"001","James","London","Accountant"},
   {"002","Laura","New York","Marketing"},
   {"003","Zack","Austin","Support"},
   {"004","Maggie","Phoenix","DevOps"}   
]

LIST B [
   {"002","09/10/2021"},
   {"004","11/24/2009"}
]

So basically I would like to use a LINQ query that would merge the results from both lists based on their ID (the first entry) to form something that would look like so:

LIST RESULT [
   {"002","Laura","New York","Marketing","09/10/2021"},
   {"004","Maggie","Phoenix","DevOps","11/24/2009"}
]

So far I've tried a few attempts and my last one didn't give me the result I was expecting:

var Result = A.Where(p => B.All(p2 => p2.Id == p.Id)).ToList();

Solution

  • You can use Join method to get expected result :

    List<A> listA = new List<A>()
    {
      new A("001", "James", "Accountant", "London"),
      new A("002", "Laura", "Marketing", "New York"),
      new A("004", "Maggie", "DevOps", "Phoenix")
    };
    
    List<B> listB = new List<B>()
    {
      new B("002", "09/10/2021"),
      new B("004", "11/24/2009")
    };
    var result = listA.Join(listB, a => a.Id, b => b.Id, (a, b) => new
    {
        a.Id,
        b.Date,
        a.Job,
        a.Name,
        a.City
    }).ToList();
    
    foreach (var item in result)
    {
        Console.WriteLine($"{item.Id} {item.Name} {item.City} {item.Job} {item.Date}");
    }
    

    A and B classes:

    public record A(string Id, string Name, string Job, string City);
    public record B(string Id, string Date);
    

    Result:

    002 Laura New York Marketing 09/10/2021
    004 Maggie Phoenix DevOps 11/24/2009