我有这个班级
class Test
{
public string Property { get; set; }
public string ID { get; set; }
public List<string> MyProperty { get; set; }
}
我创建了它的实例
List<Test> t = new List<Test>() {
new Test() {
ID = "1",
Property = "2"
},
new Test() {
ID = "2",
Property = "3"
},
new Test() {
ID = "2",
Property = "5"
}
};
我希望有一个List,其中包含按ID过滤的不同元素,以及公共List MyProperty {get;组;应填充公共字符串Property {get;组;数据。
所以最后的结果应该是
List<Test> = {
1. ID = "1",List<MyProperty> = "2"
2. ID = "2",List<MyProperty> = "2"
};
答案 0 :(得分:4)
您可以使用GroupBy
和First
删除重复项:
t.GroupBy(x => x.Id)
.Select(g => g.First())
.ToList();
答案 1 :(得分:2)
我会使用GroupBy()
LINQ扩展名:
t.GroupBy(x => x.ID)
.Select(x => new Test {
ID = x.Key,
MyProperty = x.Select(y => y.Property).ToList()
})
.ToList();
GroupBy
的参数是您想要分组的密钥,在您的情况下是ID。
然后Select
会将它们投射到新的Test
以下是一些有用的链接:
https://msdn.microsoft.com/en-us/library/bb545971.aspx
https://msdn.microsoft.com/en-us/library/bb534304(v=vs.110).aspx
结果将是:
[
{
"ID": "1",
"MyProperty": [ "2" ],
"Property": null
},
{
"ID": "2",
"MyProperty": [ "3", "5" ],
"Property": null
},
]
答案 2 :(得分:2)
t.Distinct(new TestComparer());
TestComparer是比较器的实现。 这是sample
// Custom comparer for the Test class
class ProductComparer : IEqualityComparer<Test>
{
// Tests are equal if their IDs are equal.
public bool Equals(Test x, Test y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.Id == y.Id;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(Test test)
{
//Check whether the object is null
if (Object.ReferenceEquals(test, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashId = test.Id == null ? 0 : test.Id.GetHashCode();
//Calculate the hash code for the test.
return hashId;
//Should be enough, but you can merge hashcodes of other fields in some way, for example:
//int hashProperty = test.Property == null ? 0 : test.Property.GetHashCode();
//return hashId ^ hashProperty;
}
}