简体   繁体   中英

join of two lists in c#

public class Co
{
    public int Id { get; set; }
    public string Title { get; set; }
    public List<string> Cards { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<Co> coll = new List<Co>();
        Co c1 = new Co();
        c1.Id = 1;
        c1.Title = "A";
        coll.Add(c1);
        Co c2 = new Co();
        c2.Id = 2;
        c2.Title = "B";
        coll.Add(c2);
        List<KeyValuePair<int, int>> list = new List<KeyValuePair<int, int>>();
        list.Add(new KeyValuePair<int, int>(1, 2));
        list.Add(new KeyValuePair<int, int>(1, 3));
        list.Add(new KeyValuePair<int, int>(1, 1));
        list.Add(new KeyValuePair<int, int>(2, 1));

        Console.ReadKey();
    }

I want to assign Cards property for all the objects in coll with comma separated values of value in list by comparing the id from object in coll with key from list

Output: for first object c.Cards ="2,3,1" for second object c.cards= "1"

I'm able to do it with foreach loops. Can anyone tell me the solution with linq?

First, note that your sample data is incorrect because you use the same c object twice. It should be like:

List<Co> coll = new List<Co>();
Co c = new Co();
c.Id = 1;
c.Title = "A";
coll.Add(c);
c = new Co(); // HERE
c.Id = 2;
c.Title = "B";
coll.Add(c);
List<KeyValuePair<int, int>> list = new List<KeyValuePair<int, int>>();
list.Add(new KeyValuePair<int, int>(1, 2));
list.Add(new KeyValuePair<int, int>(1, 3));
list.Add(new KeyValuePair<int, int>(1, 1));
list.Add(new KeyValuePair<int, int>(2, 1));

Now, note that your Cards property is a List<string> , not a string , so I don't know what you mean by "comma separated values". If Cards were a string:

coll.ForEach(co => co.Cards = String.Join(",",
    list.Where(l => l.Key == co.Id)
        .Select(l => l.Value)));

With you current definition as List<string> :

coll.ForEach(co => co.Cards =
    list.Where(l => l.Key == co.Id)
        .Select(l => l.Value.ToString()).ToList()
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM