问题描述
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
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
输出:对于第一个对象c.Cards ="2,3,1" 对于第二个对象c.cards =" 1"
Output: for first object c.Cards ="2,3,1" for second object c.cards= "1"
我可以通过foreach循环来做到这一点.谁能告诉我使用linq的解决方案?
I'm able to do it with foreach loops. Can anyone tell me the solution with linq?
推荐答案
首先,请注意您的示例数据不正确,因为您两次使用同一c
对象.应该是这样的:
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));
现在,请注意,您的Cards
属性是List<string>
,而不是string
,因此我不知道逗号分隔值"的含义.如果Cards
是字符串:
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)));
您当前的定义为List<string>
:
coll.ForEach(co => co.Cards =
list.Where(l => l.Key == co.Id)
.Select(l => l.Value.ToString()).ToList()
);
这篇关于C#中两个列表的联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!