Linq 获取 Distinct ToDictionary
需要帮助才能仅根据 i.Code 选择/获取不同的条目。 有重复项,因此我的表达式中出现错误“已添加具有相同键的项目。”
var myDictionary = dbContext.myDbTable
.Where(i => i.shoesize>= 4)
.OrderBy(i => i.Code)
.ToDictionary(i => i.Code, i => i);
尝试以不同的组合以及它们本身使用 Select 和/或 Distinct但我仍然遇到同样的错误
var myDictionary= dbContext.myDbTable
.Where(i => i.shoesize>= 4)
.OrderBy(i => i.Code)
//.Select(i => i)
//.Distinct()
.ToDictionary(i => i.Code, i => i);
有人可以帮忙吗? C#
更新:如果有多个具有相同代码的对象,我只想将第一个对象(具有该特定代码)添加到 myDictionary 中。
need help to only select/get distinct entries based on i.Code.
There are duplicates and thus I'm getting an error in my expression "An item with the same key has already been added."
var myDictionary = dbContext.myDbTable
.Where(i => i.shoesize>= 4)
.OrderBy(i => i.Code)
.ToDictionary(i => i.Code, i => i);
Have tried to use Select and/or Distinct in different combinations and also by themselves but am still getting the same error
var myDictionary= dbContext.myDbTable
.Where(i => i.shoesize>= 4)
.OrderBy(i => i.Code)
//.Select(i => i)
//.Distinct()
.ToDictionary(i => i.Code, i => i);
Can anybody help? C#
UPDATE: If there are multiple objects with the same code I only want to add the first object(with that particular code) to myDictionary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以按
Code
进行分组,并从每个组中选择第一项(相当于不同的):您不需要
OrderBy
,因为Dictionary
>s 代表无序集合。如果您需要有序字典,可以使用SortedDictionary
。You can group by
Code
and select the first item from each group (which is equivalent to distinct):You don't need the
OrderBy
sinceDictionary
s represent an unordered collection. If you need an ordered dictionary you could useSortedDictionary
.在我看来,您正在寻找的是
.DistinctBy()
(在 .NET 6 中提供),它允许您指定通过哪个属性来区分集合中的元素:It sounds to me that what you are looking for is
.DistinctBy()
(available in .NET 6), which lets you specify which property to distinct the elements in your collection by:通过将其划分并首先创建一个列表,与将其全部捆绑到一个 linq 中相比,它的工作原理是,猜测 First() 需要将其放入列表中才能将其放入字典中。
然后
By dividing it and creating a list first it worked as compared to when it was all bundled up into one linq, guess the First() needed it to be in a list before being able to make it into a dict.
then