Reputation: 1789
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);
Upvotes: 1
Views: 3024
Reputation: 241651
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.
Upvotes: 2
Reputation: 50728
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.
Upvotes: 0