[英]Select Distinct in Linq with anonymous type
考虑此LINQ查询。 当给定的blobID.Key
出现多个时,将导致错误。
有什么方法可以在此处添加与众不同的内容,以安全的方式将其转换为字典吗?
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
被匿名类覆盖,因此您可以使用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);
在这里, Distinct
将为匿名类使用Default
相等比较器。 匿名类的Default
相等比较器使用Object.Equals
,如果所有属性都相等,则重写该对象以返回true。
使用ToLookup
。 这是为此而做的。
是的,因为密钥必须是唯一的,所以字典将是一个问题。 您可以考虑使用不具有此要求的另一种结构来存储数据(列表),或者可以尝试使用@Jason提到的Distinct(),或按键分组,然后创建该组的字典。 这样,密钥是唯一的,并且您将使用该给定密钥存储所有条目的集合。
取决于您的要求。
HTH。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.