使用LINQ从列表中获取第一条记录

时间:2018-07-18 22:03:46

标签: c# linq

我正在尝试使用LINQ从产品列表中获得价格最高的产品

Product Name     Product Category        Product Price
Mobile           Electronics             $300
Fridge           Electronics             $2500
chair            Furniture               $25
Table            Furniture               $80
Shirt            Clothing                $15
Pant             Clothing                $35

所需的输出是

电子冰箱2500

我尝试按照以下方法在foreach中使用break。

如何在不中断的情况下实现这一目标?

var highCost = from highPrice in listProduct
           orderby highPrice.ProductPrice descending
           select highPrice;

 foreach(var item in highCost) {
    Console.WriteLine("{0}      {1}     {2}", item.ProductCategory, 
         item.ProductName, item.ProductPrice);
    break;
}

3 个答案:

答案 0 :(得分:1)

看来,您以某种错误的方式使用了TWIGFirst

这应该可以解决问题:

FirstOrDefault

或者,如果愿意,可以使用查询语法:

var item = listProduct.OrderByDescending(e => e.ProductPrice).FirstOrDefault();
if (item != null)
{
    Console.WriteLine("{0}      {1}     {2}", item.ProductCategory, 
         item.ProductName, item.ProductPrice);
}

答案 1 :(得分:0)

以下是产品类别

class Product
{
    public int ID{set;get;}
    public string Name { set; get; }
    public string Category { set; get; }
    public string PriceDollar { set; get; }
}

用于用三个记录填充列表的代码,以便您清楚地理解,例如

List<Product> list = new List<Product>();
        Product p1 = new Product();
        p1.ID = 1;
        p1.Name = "Mobile";
        p1.Category = "Electronics";
        p1.PriceDollar = "200";
        Product p2 = new Product();
        p2.ID = 2;
        p2.Name = "Mobile";
        p2.Category = "Electronics";
        p2.PriceDollar = "400";
        Product p3 = new Product();
        p3.ID = 3;
        p3.Name = "Chair";
        p3.Category = "Furniture";
        p3.PriceDollar = "100";

        list.Add(p1);
        list.Add(p2);
        list.Add(p3);

要获取产品列表的第一条记录,请使用以下代码,因为我得到了价格的结果200,并显示在MessageBox中。

var query = from hightPrice in list select hightPrice.PriceDollar;
        var firstRecordPrice = query.First();
        MessageBox.Show(firstRecordPrice);

以下代码将用于从显示400的结果的产品列表中获取最高价格

var maxPrice = list.Max(p=>p.PriceDollar);
        MessageBox.Show(maxPrice);

答案 2 :(得分:0)

您可以使用略有不同的方法来获得更好的O(N)运行时间:

var productWithMaxPrice = listProduct.Aggregate((max, product) => 
    max.ProductPrice >= product.ProductPrice ? max : product);

LINQ方法OrderByDescending使用的Quicksort算法的O(N * logN)运行时更糟。