我有一个如下所示的对象
public class SampleObject
{
public int MsfId { get; set; }
public List<string> PgId { get; set; }
public List<string> DcId { get; set; }
}
在上面的聚合中,按
PgId
分组的MsfId
值。 DcId
也是如此。例如:
MsfId: 100
PgId: "abc"
DcId: "123"
MsfId: 100
PgId: "def"
DcId: "456"
MsfId: 100
PgId: "ghi"
DcId: "789"
MsfId: 101
PgId: "abc"
DcId: "123"
如何编写一个LINQ查询来聚合它并创建如下的SampleObjects列表?
MsfId: 100
PgId: "abc", "def", "ghi"
DcId: "123", "456", "789"
MsfId: 101
PgId: "abc"
DcId: "123"
最佳答案
尝试像这样的聚合:
var result = col.GroupBy(x => x.MsfId)
.Select(x => new SampleObject {
MsfId = x.Key,
PgCodes = x.Select(t=>t.PgId).ToList(),
DcCodes = x.Select(t=>t.DcId).ToList()
});