[英]Get distinct list objects from list using LinQ
I am having list of Item. 我有物品清单。
class Item{
public int Year { get; set; }
public int QuarterIndex { get; set; }
}
How to convert List to distinct List? 如何将列表转换为不同的列表?
Source: 资源:
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}
};
Result: 结果:
target = new List<Item>(){
new Item(){ Year = 2013, QuarterIndex = 1},
new Item(){ Year = 2013, QuarterIndex = 2},
new Item(){ Year = 2013, QuarterIndex = 3}
};
Here's a simple but potentially less efficient way which works without modifying the class itself: 这是一种简单但可能效率较低的方法,无需修改类本身即可工作:
items = items.GroupBy(i => new { i.Year, i.QuarterIndex })
.Select(g => g.First())
.ToList();
Another way is to implement a custom IEqualityComparer<Item>
which you can use for Distinct
(and other methods in Enumerable
class): 另一种方法是实现可用于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;
}
}
}
Now this works: 现在这有效:
items = items.Distinct(new ItemComparer()).ToList();
If you can/want to modify the original class you can override Equals
+ GetHashCode
: 如果您可以/想要修改原始类,则可以重写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;
}
}
}
Then Distinct
works "automagically": 然后Distinct
可以“自动”工作:
items = items.Distinct().ToList();
This code helps you, 此代码可以帮助您,
objlist.Where(w => w.ColumnName != "ColumnValue").GroupBy(g => new { g.Value, g.Name }).
Select(s=> new ClassName(s.Key.Value, s.Key.Name)).ToList()
Happy Coding :) 快乐编码:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.