[英]How to getting distinct values by linq or lambda?
我有一個項目列表,我嘗試通過不同的鍵獲取唯一的項目。 班級:
class TempClass
{
public string One { get; set; }
public string Two { get; set; }
public string Key
{
get
{
return "Key_" + One + "_" + Two;
}
}
}
我按如下方式構建虛擬列表:
List<TempClass> l = new List<TempClass>()
{
new TempClass(){ One="Da" , Two = "Mi"},
new TempClass(){ One="Da" , Two = "Mi"},
new TempClass(){ One="Da" , Two = "Mi"},
new TempClass(){ One="Mi" , Two = "Da"},
new TempClass(){ One="Mi" , Two = "Da"},
};
我的問題是 - 如何只獲得1項? 通過檢查確實只存在唯一鍵? 唯一項目是否應該檢查是否只有一個鍵等於“Key_Da_Mi”或“Key_Mi_Da”?
怎么實現呢?
將包含兩個鍵的字符串的HashSet
上的每個項目分組,使用HashSet的set comparer將項目比較為集合(集合是無序的),然后從每個組中拉出第一個(或任何一個)項目:
var distinct = l.GroupBy(item => new HashSet<string>() { item.One, item.Two },
HashSet<string>.CreateSetComparer())
.Select(group => group.First());
您應該實現相等比較,或者使用您的特定邏輯實現IEqualityComparer<T>
:
class TempClassEqualityComparer : IEqualityComparer<TempClass>
{
public bool Equals(TempClass x, TempClass y)
{
if (Object.ReferenceEquals(x, y)) return true;
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
// For comparison check both combinations
return (x.One == y.One && x.Two == y.Two) || (x.One == y.Two && x.Two == y.One);
}
public int GetHashCode(TempClass x)
{
if (Object.ReferenceEquals(x, null)) return 0;
return x.One.GetHashCode() ^ x.Two.GetHashCode();
}
}
然后你可以在Distinct
方法中使用這個比較器:
var result = l.Distinct(new TempClassEqualityComparer());
只需在創建密鑰之前訂購它們。
public string Key
{
get{
List<string> l = new List<string>{One, Two};
l = l.OrderBy(x => x).ToList();
return "Key_" + string.Join("_", l);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.