2 回答
TA贡献1797条经验 获得超6个赞
跟
using System.Collections;
using System.Collections.Generic;
你可以创建一个类,如
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>>
编辑:
在评论之后,我意识到这不起作用(我曾经想过)!它适用于和诸如.所以上面的类需要改成: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贡献1845条经验 获得超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 关注
- 71 浏览
添加回答
举报