簡體   English   中英

使用LinQ從列表中獲取不同的列表對象

[英]Get distinct list objects from list using LinQ

我有物品清單。

class Item{
      public int Year { get; set; }
      public int QuarterIndex { get; set; }
}

如何將列表轉換為不同的列表?

資源:

List<Item> items = new List<Item>(){
 new Item(){ Year = 2013, QuarterIndex = 1},
 new Item(){ Year = 2013, QuarterIndex = 2},
 new Item(){ Year = 2013, QuarterIndex = 3},
 new Item(){ Year = 2013, QuarterIndex = 1}
};

結果:

target = new List<Item>(){
 new Item(){ Year = 2013, QuarterIndex = 1},
 new Item(){ Year = 2013, QuarterIndex = 2},
 new Item(){ Year = 2013, QuarterIndex = 3}
};

這是一種簡單但可能效率較低的方法,無需修改類本身即可工作:

items = items.GroupBy(i => new { i.Year, i.QuarterIndex })
    .Select(g => g.First())
    .ToList();

另一種方法是實現可用於Distinct (以及Enumerable類中的其他方法)的自定義IEqualityComparer<Item>

public class ItemComparer : IEqualityComparer<Item>
{
    public bool Equals(Item lhs, Item rhs)
    {
        if(lhs == null || rhs == null) return false;
        return lhs.Year == rhs.Year && lhs.QuarterIndex == rhs.QuarterIndex;
    }

    public int GetHashCode(Item item)
    {
        if(item == null) return 0;
        unchecked
        {
            int hash = 23;
            hash = (hash * 31) + item.Year;
            hash = (hash * 31) + item.QuarterIndex;
            return hash;
        }
    }
}

現在這有效:

items = items.Distinct(new ItemComparer()).ToList();

如果您可以/想要修改原始類,則可以重寫Equals + GetHashCode

public class Item
{
    public int Year { get; set; }
    public int QuarterIndex { get; set; }

    public override bool Equals(object otherItem)
    {
        Item other = otherItem as Item;
        if (other == null) return false;
        return this.Equals(other);
    }

    public bool Equals(Item otherItem)
    {
        if(otherItem == null) return false;
        return Year == otherItem.Year && QuarterIndex == otherItem.QuarterIndex;
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 23;
            hash = (hash * 31) + Year;
            hash = (hash * 31) + QuarterIndex;
            return hash;
        }
    }
}

然后Distinct可以“自動”工作:

items = items.Distinct().ToList();

此代碼可以幫助您,

objlist.Where(w => w.ColumnName != "ColumnValue").GroupBy(g => new { g.Value, g.Name }).
                 Select(s=> new ClassName(s.Key.Value, s.Key.Name)).ToList()

快樂編碼:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM