对象链接:Distinct + concatation
本文关键字:concatation Distinct 链接 对象 | 更新日期: 2023-09-27 18:10:41
我有一个对象列表,其中9个属性中有8个经常重复,最后一个属性始终不同。
使用c#和LINQ对对象,我想检索(分组)不同的前8个属性的列表,第9个属性跨组连接…
public class MyClass
{
public int property1 {get;set;}
public string property2 {get;set;}
public string property3 {get;set;}
}
我可能有一个列表,如:
var list1 = new List<myClass>
{
new myClass {property1 = 1, property2 = "foo", property3 = "This"},
new myClass {property1 = 1, property2 = "foo", property3 = "is"},
new myClass {property1 = 1, property2 = "foo", property3 = "a"},
new myClass {property1 = 1, property2 = "foo", property3 = "test"},
new myClass {property1 = 1, property2 = "foo", property3 = "value"},
new myClass {property1 = 2, property2 = "bar", property3 = "Here's"},
new myClass {property1 = 2, property2 = "bar", property3 = "a"},
new myClass {property1 = 2, property2 = "bar", property3 = "second"}
};
我正在努力编写最高性能的LINQ表达式,它将产生以下对象列表:
{
{property1 = 1, property2 = "foo", newProperty3 = "This is a test value"},
{property1 = 2, property2 = "bar", newProperty3 = "Here's a second"}
};
有人介意帮忙吗?
您要查找的是具有复合键的GroupBy
查询:
list1.GroupBy(x => new { x.property1, x.property2 })
.Select(g => new
{
property1 = g.Key.property1,
property2 = g.Key.property2,
newProperty3 = string.Join(" ", g.Select(x => x.property3))
});