2016-08-12 61 views
0

我有这个类如何从列表中选择不同的项目

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" 
       } 

      }; 

我想有具有由ID filteried不同的元素列表中的实例,并也公开List MyProperty {get;组; }应该填充公共字符串Property {get;组; }数据。

所以最终的结果应该是

List<Test> = { 
    1. ID = "1",List<MyProperty> = "2" 
    2. ID = "2",List<MyProperty> = "2"       

}; 
+0

'名单'你说'名单 MyPropertyList'?您不能使用变量的名称作为类型。 –

回答

3

您可以使用GroupByFirst删除重复:

t.GroupBy(x => x.Id) 
    .Select(g => g.First()) 
    .ToList(); 
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 
    }, 
] 
1
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; 
    } 
} 
+0

请在这里插入示例... :) –

+0

没问题,这里是;) – GothicSecret