Dra*_*mmy 2 c# linq linq-to-objects
我有一个对象列表,其中9个属性中的8个频繁重复,最后一个属性在整个过程中不同.
使用C#和LINQ对象我想检索前8个属性的(分组)不同列表,其中第9个属性在整个组中连接...
public class MyClass
{
public int property1 {get;set;}
public string property2 {get;set;}
public string property3 {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
我可能有一个列表,如:
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"}
};
Run Code Online (Sandbox Code Playgroud)
我正在努力编写能够生成以下对象列表的最高性能的LINQ表达式:
{
{property1 = 1, property2 = "foo", newProperty3 = "This is a test value"},
{property1 = 2, property2 = "bar", newProperty3 = "Here's a second"}
};
Run Code Online (Sandbox Code Playgroud)
有人会介意帮忙吗?
您正在寻找的是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))
});
Run Code Online (Sandbox Code Playgroud)