我有一个包含这种形式的 600 多个对象的列表:
每个对象都有一个 ItemCode
属性和一个 ItemCost
属性
我正在尝试编写 C# 语言集成查询 (LINQ) 以
在此列表中查找具有相同 ItemCode 的项目。
并删除 ItemCost 较高的那个。
例如,如果此列表中有 2 个项目具有相同的 ItemCode = RNWA。
如果其中一个的 ItemCost 为 4.65,另一个的 ItemCost 为 3
我想删除 ItemCost 较高的 4.65
我的第一种方法是查找/选择 ItemCode 出现多次的项目。
以下是我的一些“失败”尝试 (where dataSet is the list of objects
)
dataSet.Select(x => x.ItemCode).Where(x => x.Count() > 1).Cast<Dictionary<string, decimal>>();
dataSet.GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g).ToList().Cast<Dictionary<string, decimal>>()
dataSet.GroupBy(x => x.ItemCode).Where(x => x.Count() > 1).Cast<Dictionary<string, decimal>>();
请谁能指点我一下。谢谢!
答案 0 :(得分:0)
结合使用 GroupBy
和 .ToDictionary
,您可以构建以 ItemCode
为键,最低 ItemCost
为值的字典。
var result = dataSet
.GroupBy(i => i.ItemCode)
.ToDictionary(group => group.Key, group => group.Min(i => i.ItemCost));