我有以下课程
public class InvoiceRO
{
public int ID{ get; set; }
public string Address { get; set; }
public string Reference1 { get; set; }
public string DNNumber { get; set; }
public string QuotationNumber { get; set; }
}
这里我的数据如下
ID Address Reference1 DNNumber QuotationNumber
----------------------------------------------------------
1 add1 ref1 d001 q001
2 add1 ref1 d001 q002
3 add1 ref1 d002 q003
我只需要一行作为输出,因此前2列值将相等并且只获得一个,最后2列将连接并以逗号分隔值检索。最终输出将是
ID Address Reference1 DNNumber QuotationNumber
----------------------------------------------------------
1 add1 ref1 d001, d002 q001, q002, q003
如何在LINQ中这样分组?
答案 0 :(得分:2)
您可以使用GroupBy
,然后将字符串与String.Join
:
invoices.GroupBy(i => new {i.Address, i.Reference1})
.Select(g => new InvoiceRO {
ID = g.First().ID,
Address = g.Key.Address,
Reference1 = g.Key.Reference1,
DNNumber = string.Join(", ", g.Select(i => i.DNNumber)),
QuotationNumber = string.Join(", ", g.Select(i => i.QuotationNumber))
}