假设我有以下列表
var list = new List<CustomClass>
{
new CustomClass {Group = "Car", Color = "White"},
new CustomClass {Group = "Motocycle", Color = "Blue"},
new CustomClass {Group = "Car", Color = "Black"},
};
如何将此列表设置为不同的Group并将Color与逗号合并,以便我的列表为:
Group Color
------------------------------------
"Car" "White, Black"
"Motocycle" "Blue"
答案 0 :(得分:3)
假设您想要一个新的CustomClass List,请使用string.join和groupby
var list = new List<CustomClass>
{
new CustomClass {Group = "Car", Color = "White"},
new CustomClass {Group = "Motocycle", Color = "Blue"},
new CustomClass {Group = "Car", Color = "Black"},
};
var results = list.GroupBy(c => c.Group).Select(g => new CustomClass()
{
Group = g.Key,
Color = String.Join(", ", g.Select(c=>c.Color))
}).ToList();
答案 1 :(得分:1)
我不确定您希望将结果存储在哪个结构中。
这将为您提供包含所需结果的字典。
var colors =
list.GroupBy(x => x.Group)
.ToDictionary(x => x.Key, x => string.Join(", ", x.Select(y => y.Color)));
答案 2 :(得分:1)
试试这个:
var query =
from x in list
group x.Color by x.Group into gcs
select new
{
Group = gcs.Key,
Colors = String.Join(", ", gcs),
};
我得到了这个结果: