如何从列表中创建字典,并将对象作为键

时间:2013-10-25 20:12:22

标签: c# linq dictionary

具体来说我想使用ToDictionary()。以下是一些示例代码:

public class Foo
{
    public int a { get; set; }
    public int b { get; set; }
    public int c { get; set; }
}

public class Key
{
    public int a { get; set; }
    public int b { get; set; }
}

public class KeyEqualityComparer : IEqualityComparer<Key>
{
    public int GetHashCode(Key k)
    {
        int hash = 17;
        hash = hash * 23 + k.a.GetHashCode();
        hash = hash * 23 + k.b.GetHashCode();

        return hash;
    }

    public bool Equals(Key lhs, Key rhs)
    {
        return ((lhs.a == rhs.a) && (lhs.b == rhs.b));
    }
}

static List<Foo> Data = new List<Foo>();
static Dictionary<Key, int> Data_Map = new Dictionary<Key, int>( new KeyEqualityComparer() );

static void Main(string[] args)
{
    Data.Add(new Foo() { a = 0, b = 0, c = 99 });
    Data.Add(new Foo() { a = 1, b = 0, c= 69 });

    // Key: new Key() { a = ???, b = ??? }
    // Value: c
    Data_Map = Data.ToDictionary(???)

}

2 个答案:

答案 0 :(得分:2)

static void Main(string[] args)
{
    Data.Add(new Foo() { a = 0, b = 0, c = 99 });
    Data.Add(new Foo() { a = 1, b = 0, c= 69 });

    // Key: new Key() { a = ???, b = ??? }
    // Value: c
    var Data_Map = Data.ToDictionary(
               x => new Key{ a = x.a, b = x.b},
               x => x.c, 
               new KeyEqualityComparer ());

}

http://msdn.microsoft.com/en-us/library/bb548554.aspx

答案 1 :(得分:-1)

Data_Map = Data.ToDitionary(key=>new Key{a = key.a, b= key.b}, 
                            value=> value.c, new KeyEqualityComparer());