Vic*_*aev 1 c# dictionary indexed list
我尝试编写一个程序,其中Dictionary由List索引.(相信我,我有,并且有选项,但我喜欢按列表编制索引).有一个最小的工作(实际上不工作,只有一个最后一行是一个问题)示例:
using System;
using System.Collections.Generic;
namespace test
{
class Program
{
static void Main(string[] args)
{
Dictionary<List<String>, int> h = new Dictionary<List<string>,int>();
List<String> w = new List<string> {"a"};
h.Add(w, 1);
w = new List<string>{"b"};
h.Add(w,2);
w = new List<string>{"a"};
int value = 0;
h.TryGetValue(w, out value);
Console.WriteLine(value+" "+h[w]);
}
}
Run Code Online (Sandbox Code Playgroud)
如果调试这个程序,他会清楚地看到h中有两个元素,但仍然无法通过正确的索引访问这些元素--- h [w].我错了还是有什么奇怪的事情发生?
您的应用程序的问题来自以下事实:
new List<String> { "a" } != new List<String> { "a" }
Run Code Online (Sandbox Code Playgroud)
列表的等同性检查以查看两个引用是否引用相同的实例.在这种情况下,他们没有.相反,你创建了两个具有相同元素的列表......这并不能使它们相等.
您可以通过创建自定义Equality Comparer来解决问题:
public class ListEqualityComparer<T> : IEqualityComparer<List<T>>
{
public bool Equals(List<T> list1, List<T> list2)
{
return list1.SequenceEquals(list2);
}
public int GetHashCode(List<T> list)
{
if(list != null && list.Length > 0)
{
var hashcode = list[0].GetHashCode();
for(var i = 1; i <= list.Length; i++)
hashcode ^= list[i].GetHashCode();
return hashcode;
}
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
然后将其传递给Dictionary构造函数:
Dictionary<List<String>, int> h =
new Dictionary<List<string>,int>(new ListEqualityComparer<String>());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
912 次 |
| 最近记录: |