2 回答
TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
跟
using System.Collections;
using System.Collections.Generic;
你可以創(chuàng)建一個(gè)類,如
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>>
編輯:
在評(píng)論之后,我意識(shí)到這不起作用(我曾經(jīng)想過(guò))!它適用于和諸如.所以上面的類需要改成: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());
}
我最初的嘗試是錯(cuò)誤的!
TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊
問(wèn)題是你比較2個(gè)對(duì)象。您需要比較其中的值。我不知道我的代碼 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)注
- 121 瀏覽
添加回答
舉報(bào)
