[英]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.