Specifically I want to use ToDictionary(). Here is some sample code:
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(???)
}
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 ());
}
Data_Map = Data.ToDitionary(key=>new Key{a = key.a, b= key.b},
value=> value.c, new KeyEqualityComparer());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.