查找名称为LINQ的价格最低的产品

本文关键字:LINQ 查找 | 更新日期: 2023-09-27 17:49:14

我是LINQ的新手,我试图在列表中找到最低价格并返回它的名称。

我一直在找,但没有找到任何我可以使用的东西。

List在class Category中,但是我必须在main中写出结果。

这是一个在Microsoft Visual Studio中的c#。

我要查找的最低价格是这样的:

public static IEnumerable<Product> GetProducts( )
    {
        List<Product> products = new List<Product>( );
        products.Add( new Product { Name = "Milk",           Price = 90,       CategoryID = 4, ID = 1 } );
        products.Add( new Product { Name = "Cheese",         Price = 130, CategoryID = 4, ID = 2 } );
        products.Add( new Product { Name = "Butter",         Price = 110, CategoryID = 4, ID = 3 } );
        products.Add( new Product { Name = "Apple juice",    Price = 230, CategoryID = 1, ID = 4 } );
        products.Add( new Product { Name = "Grape juice",    Price = 240, CategoryID = 1, ID = 5 } );
        products.Add( new Product { Name = "Beetroot juice", Price = 300, CategoryID = 1, ID = 6 } );
        products.Add( new Product { Name = "Carrot juice",   Price = 190, CategoryID = 1, ID = 7 } );
        products.Add( new Product { Name = "Ginger ale",     Price = 990, CategoryID = 1, ID = 8 } );
        products.Add( new Product { Name = "Oregano",        Price = 500, CategoryID = 2, ID = 9 } );
        products.Add( new Product { Name = "Salt",           Price = 550, CategoryID = 2, ID = 10 } );
        products.Add( new Product { Name = "Pepper",         Price = 490, CategoryID = 2, ID = 11 } );
        products.Add( new Product { Name = "Carrots",        Price = 300, CategoryID = 3, ID = 12 } );
        products.Add( new Product { Name = "Spinach",        Price = 250, CategoryID = 3, ID = 13 } );
        products.Add( new Product { Name = "Onion",          Price = 200, CategoryID = 3, ID = 14 } );
        products.Add( new Product { Name = "Garlic",         Price = 150, CategoryID = 3, ID = 15 } );
        products.Add( new Product { Name = "Tomatoes",       Price = 100, CategoryID = 3, ID = 16 } );
        return products;
    }

查找名称为LINQ的价格最低的产品

from p in Products where p.Price == Products.Min(x=>x.Price) select p.Name

Ordered列表中取出First的问题是,它没有处理多个项目具有相同最低价格的可能性。

products.OrderBy(p => p.Price).Select(p => p.Name).First();

products.OrderBy(p => p.Price).First().Name;

返回Milk

string namesOfProductWithLowestPrice =  products
        .GroupBy(p => p.Price)
        .OrderBy(g => g.Key)
        .Select(g => string.Join(",",  g.Select(p => p.Name)))
        .FirstOrDefault();

如果有多个价格最低的产品,它将用逗号将名称连接起来。

EDIT在Tim Schmelters评论Ralph shillington的答案后,我已经更改了答案,Ralph shillington的答案与我的答案非常相似,但语法不同。

int lowestPrice = from prod in GetProducts()
                  select prod.Price).Min();                             
var lowestPriceProduct = from p in GetProducts()
                         where lowestPrice == p.Price)
                         select p;