2 回答

TA貢獻(xiàn)1797條經(jīng)驗 獲得超6個贊
跟
using System.Collections;
using System.Collections.Generic;
你可以創(chuàng)建一個類,如
sealed class ListComparer : EqualityComparer<List<string>>
{
public override bool Equals(List<string> x, List<string> y)
=> StructuralComparisons.StructuralEqualityComparer.Equals(x, y);
public override int GetHashCode(List<string> x)
=> StructuralComparisons.StructuralEqualityComparer.GetHashCode(x);
}
然后將其用作Dictionary<,>
myDict = new Dictionary<List<string>, Actions>(new ListComparer());
該類也可以是泛型的。ListComparersealed class ListComparer<T> : EqualityComparer<List<T>>
編輯:
在評論之后,我意識到這不起作用(我曾經(jīng)想過)!它適用于和諸如.所以上面的類需要改成:StructuralEqualityComparerList<string>string[]Tuple<string, string, ...>
sealed class ListComparer : EqualityComparer<List<string>>
{
public override bool Equals(List<string> x, List<string> y)
=> StructuralComparisons.StructuralEqualityComparer.Equals(x?.ToArray(), y?.ToArray());
public override int GetHashCode(List<string> x)
=> StructuralComparisons.StructuralEqualityComparer.GetHashCode(x?.ToArray());
}
我最初的嘗試是錯誤的!

TA貢獻(xiàn)1845條經(jīng)驗 獲得超8個贊
問題是你比較2個對象。您需要比較其中的值。我不知道我的代碼 vb.net 是c#(LINQ)。像這樣做。
var myDic = new Dictionary<List<string>, Actions>();
myDic.Add(new List<string>() { "Huey", "Dewey" }, Actions.Sleeping);
myDic.Add(new List<string>() { "Dewey", "Louie" }, Actions.Playing);
var newList = new List<string>() { "Dewey", "Louie" };
if (myDic.Keys.Any(key =>
{
if (key.Count != newList.Count) return false;
var same = true;
for (int i = 0; i < newList.Count; i++)
{
if (key[i] != newList[i]) same = false;
}
return same;
}))
MsgBox("myDict contains the list of String, as Key Value");
else
MsgBox("myDict don't contains the list of String, as Key Value")
- 2 回答
- 0 關(guān)注
- 107 瀏覽
添加回答
舉報