简体   繁体   中英

How to sort decimal values in linq

Data:

14.20
15.50
16.70

Code:

 getProductWithAllFiltersResponse
    .getProductWithAllFilters
    .OrderBy(x => x.ProductCustomModel.OrderBy(y => y.PriceWithDiscount))
    .ToList();

I am unable to sort by PriceWithDiscount

You can't sort by cursor ( IQueryable<T> , IEnumerable<T> ):

 .OrderBy(x => x.ProductCustomModel.OrderBy(y => y.PriceWithDiscount))

Imagine, that x.ProductCustomModel.OrderBy(y => y.PriceWithDiscount) returns 7 items for each product. How should we sort products then? You, probably, want something like this:

 var result = getProductWithAllFiltersResponse
   .getProductWithAllFilters
   .OrderBy(x => x.ProductCustomModel.Min(y => y.PriceWithDiscount))
   .ToList();

we sort by the best ( Min ) price with discount

Try below code to sort your list ascending and descending order.

Ascending order:

 getProductWithAllFiltersResponse
.getProductWithAllFilters
.OrderBy(y => y.PriceWithDiscount)   // Order by Asc
.ToList(); 

Descending order:

 getProductWithAllFiltersResponse
.getProductWithAllFilters
.OrderByDescending(y => y.PriceWithDiscount)   // Order by Desc
.ToList();
public class Products
{
    public string ProductName { get; set; }
    public double DiscountPrice { get; set; }
}

List<Products> lstProduct = new List<Products>();
        lstProduct.Add(new Products { ProductName = "Product1", DiscountPrice = 50.52 });
        lstProduct.Add(new Products { ProductName = "Product2", DiscountPrice = 49.50 });
        lstProduct.Add(new Products { ProductName = "Product3", DiscountPrice = 52.53 });
        lstProduct.Add(new Products { ProductName = "Product4", DiscountPrice = 100.00});
        lstProduct.Add(new Products { ProductName = "Product5", DiscountPrice = 40.40 });
        foreach (var item in lstProduct.OrderBy(d => d.DiscountPrice))
        {
            item.ProductName.ToString();
        }

尝试这个:

var prods = lstProduct.OrderBy(d => Convert.ToDouble(d.DiscountPrice)*100);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM