简体   繁体   中英

Select Distinct in Linq with anonymous type

Consider this LINQ query. It results with an error when a given blobID.Key appears more than one.

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 :

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. The Default equality comparer for an anonymous class uses Object.Equals which is overridden to return true iff all the properties are equal.

Use 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. THis way, the key is unique, and you store a collection of all entries with that given key.

Depends on your requirements.

HTH.

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.

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