我有这样的需求,需要将数据分组到OrderNum中,价格需要合并在一行中,用分号分隔,这是由Type决定的。我可以通过迭代结果来做到这一点,但是,可能有更好的方法来做到这一点,特别是在LINQ中。
var notebooks = new List<NoteBook>
{
new NoteBook { Type = 1, Currency = "USD", Price = 1000, OrderNum = "123" },
new NoteBook { Type = 2, Currency = "USD", Price = 2000, OrderNum = "123" },
new NoteBook { Type = 0, Currency = "USD", Price = 3000, OrderNum = "456" },
new NoteBook { Type = 0, Currency = "USD", Price = 4000, OrderNum = "789" },
new NoteBook { Type = 4, Currency = "USD", Price = 5000, OrderNum = "753" }
};
var results = from r in notebooks
group r by new { r.OrderNum } into g
select new
{
Currency = g.First().Currency,
OrderNum = g.First().OrderNum,
Price = ???
};
我正在等待
的结果Currency OrderNum Price
USD 123 1000; 2000
USD 456 3000
USD 789 4000
USD 753 5000
从你的描述中不确定这里应该如何使用Type,但是要形成一个单一的价格行,你可以使用String.Join
:
Price = String.Join(";", g.Select(x => x.Price))
如果你运行的是。net 4.0之前的版本,请确保将第二个参数转换为数组:
Price = String.Join(";", g.Select(x => x.Price).ToArray())