我有一个对象列表,其中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"}
};
有人会介意帮忙吗?
答案 0 :(得分:5)
您要查找的是带有复合键的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))
});