c# - 查找链表中的最小值
问题描述
所以我有两个链表:一个包含所需的项目,另一个链表包含项目列表。
因此,包含所需输出项的链表:
Required item: Automobilis | Amount needed: 1
Required item: Kirvis | Amount needed: 2
Required item: Piesiniai | Amount needed: 2
另一个链接列表,其中包含我拥有的所有项目
Item name: Automobilis | Amount available: 1 | Price of item: 3000
Item name: Automobilis | Amount available: 1 | Price of item: 5000
Item name: Rubai | Amount available: 20 | Price of item: 80
Item name: Lemputes | Amount available: 3 | Price of item: 700
Item name: Piesiniai | Amount available: 1 | Price of item: 2000
Item name: Piesiniai | Amount available: 1 | Price of item: 1800
Item name: Kirvis | Amount available: 50 | Price of item: 100
我正在尝试对所需的项目和我拥有的项目进行排序,查看名称是否匹配,如果它们匹配,我想将它们添加到新的链接列表中。
我的链接列表看起来像这样
static void FormingNewList(LinkedList<Warehouse> house, LinkedList<Order> order, LinkedList<MatchingItems> match)
{
double min = house.First().Price;
int count = 0;
foreach (Order ord in order)
{
foreach(Warehouse store in house)
{
if(ord.Title == store.Title)
{
string nam = store.Title;
int am = store.Amount;
double price = store.Price;
int id = count++;
MatchingItems add = new MatchingItems(nam, am, price, id);
match.AddLast(add);
}
}
}
}
它输出:
Name of item: Automobilis |Amount of said item available: 1 |Price of item: 3000
Name of item: Automobilis |Amount of said item available: 1 |Price of item: 5000
Name of item: Kirvis |Amount of said item available: 50 |Price of item: 100
Name of item: Piesiniai |Amount of said item available: 1 |Price of item: 2000
Name of item: Piesiniai |Amount of said item available: 1 |Price of item: 1800
我如何才能只找到给定项目的最低价格。因此,例如,如果我有一辆价值 5000 的汽车和另一辆价值 3000 的汽车,我想选择最低的价格。
所以所需的输出将是:
Item: Automobilis | Amount: 1 | Price: 3000
Item: Piesiniai | Amount: 1 | Price: 1800
Item: Kirvis | Amount: 50 | Price: 100
解决方案
如果我理解,您想按名称对产品进行分组,然后选择该项目的最低价格。您可以使用GroupBy
按项目名称分隔列表,然后Select
按价格排序后组中的第一个项目(从低到高)。
var SmallestValues = Items.GroupBy(i => i.Name)
.Select(group => group.OrderBy(x => x.Price).FirstOrDefault());
推荐阅读
- git - GIT 忽略 .gitignore
- javascript - 使用 Chart.Js 从数组中绘制散点图
- wordpress - Web Scraping - XPath - 在 div 中查找特定标签的所有元素
- dart - 通过 InkWell onTap 从其父级更改材质的颜色属性
- c - main() 包装器启动 wmain() 程序以从命令行编译它
- json - 用于查找主机和设备的最新快照的 JSON 查询?
- email - 使用编码字的 MIME 标头中的换行符是否合法?
- elasticsearch - 无法使用休眠搜索中的@Spatial 找到 geo_point 字段
- javascript - 在 Node.js 的微服务框架中使用 ES6 'import' 而不是 'require'
- javascript - Vue.js - Vuex: why is an action dispatched when I import my module stores to a helper file?