在c#中连接两个列表

时间:2013-04-13 22:13:58

标签: c# linq

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();
    }

我想通过比较coll中对象的ID与来自{{1}的密钥,为list中所有对象的Cards属性分配逗号分隔值coll }

输出:对于第一个对象c.Cards =“2,3,1”         对于第二个对象c.cards =“1”

我能用foreach循环做到这一点。谁能告诉我linq的解决方案?

1 个答案:

答案 0 :(得分:2)

首先,请注意您的示例数据不正确,因为您使用相同的c对象两次。应该是这样的:

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));

现在,请注意您的Cards属性是List<string>,而不是string,所以我不知道“逗号分隔值”是什么意思。如果Cards是字符串:

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

当前定义为List<string>

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