-1

授業がある:

public class Item
{
    public List<int> val { get; set; }
    public string info { get; set; }
}
public class IndexedDictionary : KeyedCollection<List<int>, Item>
{
    protected override List<int> GetKeyForItem(Item item)
    {
        return item.val;
    }
}

'main()'メソッドの場合:

    IndexedDictionary dic = new IndexedDictionary();
    dic.Add(new Item() { val = new List<int>() { 1, 2, 3 }, info = "Hello" });
    dic.Add(new Item() { val = new List<int>() { 1 }, info = "Bla.." });
    Console.WriteLine(dic[0].info);
    Console.WriteLine(dic[new List<int>() { 1 }].info);
    Console.ReadLine();

次の行でエラーが発生します:

        Console.WriteLine(dic[new List<int>() { 1 }].info);

私のコードを修正できますか?すべてのTks

4

3 に答える 3

2

ここで犯している間違いList<int>は、同じ が含まれているため、 a の 2 つのインスタンスが同じであると想定していることintです。そうではありません。2 つの完全に異なるインスタンスです。

new List<int>() { 1 }したがって、ローカル変数に を割り当て、その変数をキーとして使用する必要があります。

何かのようなもの:

var l1 = new List<int>() { 1 };
dic.Add(new Item() { val = l1, info = "Bla.." });
于 2012-11-14T14:36:52.467 に答える
1

リストを比較するとき、辞書はシーケンスではなくインスタンス (デフォルト) を比較します。たとえば、以下のコードはfalseを返します

bool b = new List<int>() { 1 }.Equals(new List<int>() { 1 })

したがって、実装する必要がありますIEqualityComparer。以下のように変更するIndexedDictionaryと機能します。

public class IndexedDictionary : KeyedCollection<List<int>, Item>
{
    public IndexedDictionary() : base(new MyEqualityComparer())
    {
    }

    protected override List<int> GetKeyForItem(Item item)
    {
        return item.val;
    }

    public class MyEqualityComparer : IEqualityComparer<List<int>>
    {
        public bool Equals(List<int> x, List<int> y)
        {
            return x.SequenceEqual(y);
        }

        public int GetHashCode(List<int> obj)
        {
            return obj.Aggregate(0, (s, x) => s ^= x.GetHashCode());
        }
    }
}
于 2012-11-14T14:44:53.347 に答える
0

2 つの異なるオブジェクトを比較しているため、失敗します。List<int>辞書はこれらのリストの内容を気にしないため、 as キーを使用してもあまり意味がありません。

例えば:

 var list1 = new List<int>() { 1, 2, 3 };
 var list2 = new List<int>() { 1, 2, 3 };

 Console.WriteLine("Equals: {0}", list1 == list2);
 Console.WriteLine("SequenceEquals: {0}", list1.SequenceEqual(list2));
 Console.Read();

1 つ目は false で、2 つ目は true です。

詳細については、次の質問を参照してください: Is there a built-in method to compare collections in C#?

于 2012-11-14T14:52:26.407 に答える