0

具体来说,我想使用 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(???)

}
4

2 回答 2

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

于 2013-10-25T20:16:08.240 回答
-1
Data_Map = Data.ToDitionary(key=>new Key{a = key.a, b= key.b}, 
                            value=> value.c, new KeyEqualityComparer());
于 2013-10-25T20:14:44.217 回答