繁体   English   中英

C#中两个列表的联接

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

我想通过比较coll对象的id与list键将coll所有对象的Cards属性分配给list中value的逗号分隔值

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

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

首先,请注意您的示例数据不正确,因为您两次使用相同的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()
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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