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

我想 通过将来自对象的 ID与来自的键进行比较,为其中的所有对象分配 Cards 属性,coll其中的值的逗号分隔值listcolllist

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

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

4

1 回答 1

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属性是 a List<string>,而不是 a 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()
);
于 2013-04-13T22:16:39.950 回答