使用自定义对象作为字典键,但按对象属性

时间:2016-04-11 06:03:03

标签: c# .net dictionary collections

我有一个班级:

public class Foo
{
    public string Name { get; set; }
    public double Value { get; set; }

    public override string ToString()
    {
        return Name;
    }
}

我需要创建一个字典,其中key是Foo的对象。像这样:

Foo foo1 = new Foo { Name = "Foo1", Value = 2.2 };
Foo foo2 = new Foo { Name = "Foo2", Value = 3.6 };

Dictionary<Foo, int> dic = new Dictionary<Foo, int>();
dic.Add(foo1, 1234);
dic.Add(foo2, 2345);

现在我想通过传递Foo.Name属性作为键从字典中获取值。像这样:

int i=dic["Foo1"];
// i==1234
i = dic["Foo2"];
// i==2345

有可能吗?或者将Foo的对象作为键传递并覆盖Equals方法的唯一方法是什么?

1 个答案:

答案 0 :(得分:2)

如果您使用Foo作为键,则还需要使用Foo索引字典。

如果您实际需要的内容很可能是Dictionary<string, int>,则可以尝试覆盖GetHashCodeEquals,以便您可以仅基于名称来比较Foo个对象:

using System.Collections.Generic;

public class Foo {
    public string Name { get; set; }
    public double Value { get; set; }

    public override string ToString() {
        return Name;
    }
    public override int GetHashCode() {
        return Name.GetHashCode();
    }
    public override bool Equals(object obj) {
        Foo other = obj as Foo;
        if (other == null) {
            return false;
        }
        return Name.Equals(other.Name);
    }
}

class Program {
    static void Main(string[] args) {

        Foo foo1 = new Foo { Name = "Foo1", Value = 2.2 };
        Foo foo2 = new Foo { Name = "Foo2", Value = 3.6 };

        Dictionary<Foo, int> dic = new Dictionary<Foo, int>();
        dic.Add(foo1, 1234);
        dic.Add(foo2, 2345);

        int i = dic[new Foo { Name = "Foo1" }];

    }
}