开发者

Creating anonymous class as custom key in dictionary

While using dictionary, i always override GetHashCode and Equals ( or provide a custom comparer to the dictionary).

What happens behind the covers when i create an anonymous class as key?

Sample Code....

 var groups=(from item in items
                 group item by new { item.ClientId, item.CustodianId, item.CurrencyId }
                   into g
                   select new {
     开发者_运维问答                Key=g.Key,                     
                     Sum=g.Sum(x => x.Cash)
                   }).ToDictionary(item=>item.Key,item=>item.Sum);

This code gives me the expected result, but i am not providing GetHashCode and Equals method for the anonymous class. Shouldn't this code fail to group my items on the basis of items in anonymous class??


Nope - the anonymous class automatically generates appropriate Equals/GetHashCode implementations.

From the C# language spec, section 7.5.10.6:

The Equals and GetHashcode methods on anonymous types override the methods inherited from object, and are defined in terms of the Equals and GetHashcode of the properties, so that two instances of the same anonymous type are equal if and only if all their properties are equal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜