我想明确地在id上合并两个或多个集合,并为每个id创建另一个属性的集合。
我有一个对象foo
public class foo
{
public int id { get; set; }
public string color { get; set; }
}
我有多个List<foo>
,其共有 id 但颜色不同
//list 1
id = 1, color = "red"
id = 2, color = "blue"
id = 3, color = "green"
id = 1, color = "blue"
id = 2, color = "orange"
//list 2
id = 1, color = "black"
id = 2, color = "amber"
id = 3, color = "red"
id = 4, color = "red"
id = 2, color = "silver"
我想使用linq来设计一个新的集合,该集合在id上是不同的,但是创建和颜色属性列表。
id = 1, color = { "red", "blue", "black" }
id = 2, color = { "blue", "orange", "amber", "silver" }
id = 3, color = { "green", "red" }
id = 4, color = { "red" }
问:如何用 linq
写出来答案 0 :(得分:3)
var colours = list.GroupBy(x => x.id)
.Select(x => new {id = x.Key, color = x.Select(y => y.color).ToList()})
.ToList();
这将为您提供所需结构中名为颜色的列表。
如果您希望颜色字段是逗号分隔的字符串,请将其更改为:
var colours = list.GroupBy(x => x.id)
.Select(x => new {id = x.Key, color = x.Select(y => y.color).ToArray().Join(",")})
.ToList();
答案 1 :(得分:3)
我想你想要一个Dictionary<int, List<string>>
:
Dictionary<int, List<string>> idColors = foos
.GroupBy(f => f.id)
.ToDictionary(g => g.Key, g => g.Select(f => f.color).ToList());
现在你可以用这种方式访问每个id的颜色:
List<string> colors = idColors[1];
Console.WriteLine(string.Join(",", colors));
答案 2 :(得分:1)
var result = List.GroupBy(g => new { g.id, g.color })
.Select(g => g.First())
.ToList();
答案 3 :(得分:1)
您可以使用下面提到的代码
var mergedList = list1.Concat(list2)
.GroupBy(person => person.id)
.Select(group => group.Aggregate(
(merged, next) => merged.Merge(next)))
.ToList();
答案 4 :(得分:1)
我认为这就是你要找的东西:
list1.Concat(list2)
.GroupBy(x => x.id)
.Select(x => new foo
{
id = x.Key,
color = string.Join(",", x.Select(g => g.color))
}).ToList();
答案 5 :(得分:1)
试试这个:
var combinedList = list1;
combinedList.AddRange(list2);
var uniqueIds = combinedList.Select(p => p.id).Distinct()
var result = new Dictionary<int, List<string>>();
uniqueIds.ForEach(i => result.Add(i, new List<string>());
combinedList.ForEach(i => result[i.id].Add(i.color);
我还没有对此进行测试,但我认为应该没问题...... 可能是一个更好的方法,但这应该让你现在工作!