Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you order by Greatest number in linq

Tags:

c#

linq

I would like to print products in order of quantity.The product with a bigger total should be first.

What am I missing here as it's NOT printing in order or total

class Program
{
    static void Main()
    {
        var products=new List<Product>
                         {
                             new Product {Name = "Apple", Total = 5},
                             new Product {Name = "Pear", Total = 10}
                         };

        var productsByGreatestQuantity = products.OrderBy(x => x.Total);

        foreach (var product in productsByGreatestQuantity)
        {
            System.Console.WriteLine(product.Name);
        }
        System.Console.Read();
    }
}

public class Product
{
    public string Name { get; set; }
    public int Total { get; set; }
}
like image 561
user9969 Avatar asked May 16 '11 04:05

user9969


People also ask

How to get Max value in LINQ Query?

In LINQ, you can find the maximum element of the given sequence by using Max() function. This method provides the maximum element of the given set of values. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#.

What is Max in Linq?

Max () function in LINQ is used to return the maximum value from the collection. With the help of Max() function, it is easy to find the maximum value from a given data source using Max () function. In the other case, we have to write the code to get the maximum value from the list of values.


2 Answers

var data = products.OrderByDescending(x => x.Total);
like image 170
Roy Dictus Avatar answered Oct 03 '22 10:10

Roy Dictus


Change:

var productsByGreatestQuantity = products.OrderBy(x => x.Total);

to:

var productsByGreatestQuantity = products.OrderByDescending(x => x.Total);
like image 23
fulvio Avatar answered Oct 03 '22 10:10

fulvio