[英]How do I group by List<int> in a Dictionary<string, List<int>> where the lists are identical?
我想使用Dictionary<string, List<int>>
,然后為字典中所有重復的List創建組。
Dictionary<string, List<int>> AllLists = new Dictionary<string, List<int>>()
{
{"one", new List<int>() {1, 2, 3, 4, 5}},
{"two", new List<int>() {1, 2, 3, 4, 5}},
{"three", new List<int>() {1, 1, 1, 1, 1}}
};
var ListGroups = AllLists.GroupBy(p => p.Value);
這應該將具有匹配列表的字典索引分為自己的組,但是它只是為字典中的每個索引創建一個組。 我究竟做錯了什么?
這將對List<int>
對象使用引用比較。 由於包含[1, 2, 3, 4, 5]
兩個List<int>
都是分別實例化的,因此它們將具有不同的引用。
請嘗試以下操作,例如:
var ListGroups = AllLists.GroupBy(p => string.Join(",", p.Value));
這將按列表的string
表示形式進行分組。 請注意,這可能不是您想要執行的操作,純粹是示范性的。
您可以使用GroupBy
方法的重載來傳遞自定義IEqualityComparer<List<int>>
,該自定義IEqualityComparer<List<int>>
實際上使用Enumerable.SequenceEqual
查看列表的內容。
這是IEqualityComparer<IEnumerable<T>>
:
class IEnumerableEqualityComparer<T> : IEqualityComparer<IEnumerable<T>>
{
public bool Equals(IEnumerable<T> a, IEnumerable<T> b)
{
return Enumerable.SequenceEqual(a, b);
}
public int GetHashCode(IEnumerable<T> source)
{
if (source == null)
{
return 0;
}
int shift = 0;
int result = 1;
foreach (var item in source)
{
int hash = item != null ? item.GetHashCode() : 17;
result ^= (hash << shift)
| (hash >> (32 - shift))
& (1 << shift - 1);
shift = (shift + 1) % 32;
}
return result;
}
}
使用方法如下:
var ListGroups = AllLists.GroupBy(p => p.Value,
new IEnumerableEqualityComparer<int>());
請注意,由於IEqualityComparer<T>
在T
是互變的,因此可以將以上代碼用於List<int>
因為它實現了IEnumerable<int>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.