smo*_*sen 6 linq group-by aggregate
鉴于以下列表:
var data = new[]
{
new {category = "Product", text = "aaaa"},
new {category = "Product", text = "bbbb"},
new {category = "Product", text = "bbbb"},
};
Run Code Online (Sandbox Code Playgroud)
如何按类别对其进行分组并返回一个具有类别的对象和放在一起的不同文本的描述?
即.想结束yp:
{
categroy="Product"
description = "aaaa,bbbb,cccc"
}
Run Code Online (Sandbox Code Playgroud)
尝试了以下GroupBy和Aggregate,但有些事情是不对的
data.GroupBy(x => x.category).Select(g => new
{
category = g.Key,
description = g.Aggregate((s1, s2) => s1 + "," + s2)
});
Run Code Online (Sandbox Code Playgroud)
TIA
Mar*_*zek 10
你为什么不使用String.Join(IEnumerable)方法?
data.GroupBy(x => x.category).Select(g => new
{
category = g.Key,
description = String.Join(",", g.Select(x => x.text))
});
Run Code Online (Sandbox Code Playgroud)
有了Aggregate你应该做以下几点:
description = g.Aggregate(string.Empty, (x, i) => x + "," + i.text)
Run Code Online (Sandbox Code Playgroud)
第一个参数设置种子起始值为String.Empty.第二个参数定义了将当前种子值(string)与当前元素(anonymous_type)连接起来的方法.
小智 9
data.GroupBy(x => x.category).Select(g => new
{
category = g.Key,
description = g.Select(x => x.text).Aggregate((s1, s2) => s1 + "," + s2)
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13541 次 |
| 最近记录: |