繁体   English   中英

如何从列表中选择不同的项目

[英]How to select distinct items from a list

我有这堂课

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过滤的不同元素的列表,以及公共列表MyProperty {get; 组; }应该用公共字符串Property {get;填充。 组; }数据。

所以最终结果应该是

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

};

您可以使用GroupByFirst删除重复项:

t.GroupBy(x => x.Id)
    .Select(g => g.First())
    .ToList();
t.Distinct(new TestComparer());

TestComparer是比较器的实现。 这是样本

// 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;
    }
}

我将使用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/zh-CN/library/bb545971.aspx

https://msdn.microsoft.com/zh-CN/library/bb534304(v=vs.110).aspx

结果将是:

[
    {
        "ID": "1",
        "MyProperty": [ "2" ],
        "Property": null
    },
    {
        "ID": "2",
        "MyProperty": [ "3", "5" ],
        "Property": null
    },
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM