首页 > 解决方案 > 查找链表中的最小值

问题描述

所以我有两个链表:一个包含所需的项目,另一个链表包含项目列表。

因此,包含所需输出项的链表:

    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

标签: c#linked-list

解决方案


如果我理解,您想按名称对产品进行分组,然后选择该项目的最低价格。您可以使用GroupBy按项目名称分隔列表,然后Select按价格排序后组中的第一个项目(从低到高)。

var SmallestValues = Items.GroupBy(i => i.Name)
                          .Select(group => group.OrderBy(x => x.Price).FirstOrDefault());

推荐阅读