我在c#中有以下 Item 对象列表:
public class Item
{
public int Id { get; set; }
public List<string> Orders { get; set; }
}
List<Item> item = new List<Item>() {
new Item() { Id = 1, Code = 23, Orders = new List<string>() { "A", "B" }},
new Item() { Id = 2, Code = 24, Orders = new List<string>() { "C", "D" }},
new Item() { Id = 1, Code = 23, Orders = new List<string>() { "E", "F" }},
new Item() { Id = 3, Code = 25, Orders = new List<string>() { "G", "H" }}
};
我想连接其Id相同的订单,因此上面列表的输出应为:
{
new Item() { Id = 1, Code = 23, Orders = new List<string>() { 'A', 'B', 'E', 'F' },
new Item() { Id = 2, Code = 24, Orders = new List<string>() { 'C', 'D' },
new Item() { Id = 3, Code = 25, Orders = new List<string>() { 'G', 'H' }
};
如何在c#中有效地完成此操作(如果可能,使用linq)?
答案 0 :(得分:7)
您希望根据其ID对项目进行分组,然后根据该组的所有Orders
创建新序列。
var query = items.GroupBy(item => item.Id)
.Select(group => new Item
{
Id = group.Key,
Orders = group.SelectMany(item => item.Orders).ToList()
});
请注意,这不是任何数据的交集。您正在获取每个组中所有数据的 union 。
答案 1 :(得分:2)
您可以按id
对项目进行分组,然后为每个id
创建新项目以连接订单:
item.GroupBy(x => x.Id)
.Select(x => new Item
{
Id = x.Key,
Orders = x.SelectMany(a => a.Orders).ToList()
}).ToList();
答案 2 :(得分:2)
看起来你想要的是这样的:
var output = items.GroupBy(i => i.Id)
.Select(g => new Item()
{
Id = g.Key
Orders = g.SelectMany(i => i.Orders)
.ToList()
});
或者在查询语法中:
var output =
from i in items
group i by i.Id into g
select new Item()
{
Id = g.Key
Orders = g.SelectMany(i => i.Orders).ToList()
};