我是LINQ的新手,我正在尝试在列表中找到最低价格并返回它的名称。
我一直在搜索,但找不到任何可以使用的东西。
List属于类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;
}
答案 0 :(得分:4)
from p in Products where p.Price == Products.Min(x=>x.Price) select p.Name
从First
列表中获取Ordered
的问题在于它没有处理具有相同最低价格的多个项目的可能性。
答案 1 :(得分:3)
products.OrderBy(p => p.Price).Select(p => p.Name).First();
或
products.OrderBy(p => p.Price).First().Name;
答案 2 :(得分:1)
这会返回Milk
string namesOfProductWithLowestPrice = products
.GroupBy(p => p.Price)
.OrderBy(g => g.Key)
.Select(g => string.Join(",", g.Select(p => p.Name)))
.FirstOrDefault();
如果多个产品的价格最低,它会用逗号连接名称。
答案 3 :(得分:0)
编辑在Tim Schmelters对Ralph Shillingtons的回答发表评论之后,我改变了答案,这与我非常相似,但语法不同。
int lowestPrice = from prod in GetProducts()
select prod.Price).Min();
var lowestPriceProduct = from p in GetProducts()
where lowestPrice == p.Price)
select p;