Home > Software engineering >  how to join 2 different list to 1 list
how to join 2 different list to 1 list

Time:10-04

How to join 2 list with linq to new list

public class list1
{
    public string ID { get; set; }
}

public class list2
{
    public string ID { get; set; }
    public string Member { get; set; }
}

public class result { get; set; }
{
    public string ID { get; set; }
    public List<list2> list2s { get; set; }
}

Inputs

list1 = {a}, {b}, {c}, {d}

list2 = {a,1}, {a,2}, {a,3}, {b,1}, {b,2}, {c,1}, {d,1}

Output

result = {a,{1,2,3}}, {b,{1,2}}, {c,{1}}, {d,{1}}

CodePudding user response:

you can use join same as this code:

var l1 = new List<list1>() 
{ 
    new list1() { ID = "a" },
    new list1() { ID = "b" }, 
    new list1() { ID = "c" },
    new list1() { ID = "d" } 
};


var l2 = new List<list2>() 
{ 
    new list2() { ID = "a" ,Member = "1" },
    new list2() { ID = "a", Member = "2" },
    new list2() { ID = "a", Member = "3" }, 
    new list2() { ID = "b", Member = "1" },
    new list2() { ID = "b", Member = "2" }, 
    new list2() { ID = "c", Member = "1" }, 
    new list2() { ID = "d", Member = "d" } 
    
};
var x = from l in l1 
        join ll in l2 on l.ID equals ll.ID 
        select new result 
        { 
            ID= ll.ID,
            list2s= l2.Where(d => d.ID == ll.ID).ToList() 
        };

but you can use another solution

  • Related