簡體   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