C# c语言中两个列表的连接# 公共类公司 { 公共int Id{get;set;} 公共字符串标题{get;set;} 公共列表卡{get;set;} } 班级计划 { 静态void Main(字符串[]参数) { List coll=新列表(); Co c1=新的Co(); c1.Id=1; c1.Title=“A”; coll.Add(c1); Co c2=新的Co(); c2.Id=2; c2.Title=“B”; coll.Add(c2); 列表=新列表(); 添加(新的KeyValuePair(1,2)); 添加(新的KeyValuePair(1,3)); 添加(新的KeyValuePair(1,1)); 添加(新的KeyValuePair(2,1)); Console.ReadKey(); }

C# c语言中两个列表的连接# 公共类公司 { 公共int Id{get;set;} 公共字符串标题{get;set;} 公共列表卡{get;set;} } 班级计划 { 静态void Main(字符串[]参数) { List coll=新列表(); Co c1=新的Co(); c1.Id=1; c1.Title=“A”; coll.Add(c1); Co c2=新的Co(); c2.Id=2; c2.Title=“B”; coll.Add(c2); 列表=新列表(); 添加(新的KeyValuePair(1,2)); 添加(新的KeyValuePair(1,3)); 添加(新的KeyValuePair(1,1)); 添加(新的KeyValuePair(2,1)); Console.ReadKey(); },c#,linq,C#,Linq,我想通过比较coll中对象的id和list中的键,为coll中的所有对象分配带有逗号分隔的值的Cards属性 输出:对于第一个对象c.Cards=“2,3,1” 对于第二个对象c.cards=“1” 我可以用foreach循环来实现这一点。有人能告诉我linq的解决方案吗?首先,请注意,您的示例数据不正确,因为您使用了相同的c对象两次。它应该是这样的: public class Co { public int Id { get; set; } public string Titl

我想通过比较
coll
中对象的id和
list
中的键,为
coll
中的所有对象分配带有逗号分隔的值的Cards属性

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


我可以用foreach循环来实现这一点。有人能告诉我linq的解决方案吗?

首先,请注意,您的示例数据不正确,因为您使用了相同的
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();
    }
当前定义为
列表


Linq=语言集成查询,尝试使用Linq执行所有操作都是不必要的,而且生成的代码可读性也不高。请参阅Julián的答案。您将从自动属性中受益匪浅它给出了此编译时错误“无法隐式将类型“string”转换为“System.Collections.Generic.List”“@user270014检查更新后的答案以获取bo”th解决方案和示例数据中的错误
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));
coll.ForEach(co => co.Cards = String.Join(",",
    list.Where(l => l.Key == co.Id)
        .Select(l => l.Value)));
coll.ForEach(co => co.Cards =
    list.Where(l => l.Key == co.Id)
        .Select(l => l.Value.ToString()).ToList()
);