简体   繁体   English

选择具有匿名类型的Linq中的Distinct

[英]Select Distinct in Linq with anonymous type

Consider this LINQ query. 考虑此LINQ查询。 It results with an error when a given blobID.Key appears more than one. 当给定的blobID.Key出现多个时,将导致错误。

Is there any way to add distinct here to convert it to dictionary in a safe way? 有什么方法可以在此处添加与众不同的内容,以安全的方式将其转换为字典吗?

var temp = (from blobID in blobIds
            join blob in blobs on blobID.Value.HashKey 
            equals blob.HashKey
            select new { blobID.Key,  
                          Binder = Load(blob)}
           ).ToDictionary(arg => arg.Key, arg => arg.Binder);

Object.Equals is overridden for anonymous classes so you can just use Enumerable.Distinct : Object.Equals被匿名类覆盖,因此您可以使用Enumerable.Distinct

var temp = (from blobID in blobIds
            join blob in blobs on blobID.Value.HashKey equals blob.HashKey
            select new {
                blobID.Key,
                Binder = Load(blob)
            }
           ).Distinct()
            .ToDictionary(arg => arg.Key, arg => arg.Binder);

Here, Distinct will use the Default equality comparer for the anonymous class. 在这里, Distinct将为匿名类使用Default相等比较器。 The Default equality comparer for an anonymous class uses Object.Equals which is overridden to return true iff all the properties are equal. 匿名类的Default相等比较器使用Object.Equals ,如果所有属性都相等,则重写该对象以返回true。

Use ToLookup . 使用ToLookup It was made for this. 这是为此而做的。

Yes, that would be an issue with the dictionary since the key has to be unique. 是的,因为密钥必须是唯一的,所以字典将是一个问题。 You could consider using another structure to store the data (a list) which doesn't have that requirement, or you could try Distinct() as @Jason mentioned, or potentially group by the key, and create a dictionary of the group. 您可以考虑使用不具有此要求的另一种结构来存储数据(列表),或者可以尝试使用@Jason提到的Distinct(),或按键分组,然后创建该组的字典。 THis way, the key is unique, and you store a collection of all entries with that given key. 这样,密钥是唯一的,并且您将使用该给定密钥存储所有条目的集合。

Depends on your requirements. 取决于您的要求。

HTH. HTH。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM