Reputation: 4596
I have following class structure
public class PriceClass
{
public int id { get; set; }
public string price { get; set; }
public int product_id { get; set; }
}
public class NameClass
{
public int id { get; set; }
public string name { get; set; }
}
public class ProductDetails
{
public int id { get; set; }
public string product_type { get; set; }
public List<NameClass> nameCl{ get; set; }
public List<PriceClass> priceCl{ get; set; }
}
public class ProductLists
{
public List<ProductDetails> ProductDet{ get; set; }
}
Now I want to sort the ProductLists with price i.e. in priceClass class
I tried with some solution but that does not seems working
prdList = (ProductLists )prdList.ProductDet.OrderBy(r => r.priceCl.OrderBy(x => x.price).ToList());
But it seems i am no where around its solution Please suggest
Thanks
Upvotes: 1
Views: 463
Reputation: 2818
You can use a custom IComparer to compare the product details.
public class ProductDetailsComparer : IComparer<ProductDetails>
{
private bool _compareMinPrice;
public ProductDetailsComparer(bool compareMinPrice)
{
_compareMinPrice = compareMinPrice;
}
public int Compare(ProductDetails x, ProductDetails y)
{
var left = _compareMinPrice ? x.priceCl.Min(p => p.price) : x.priceCl.Max(p => p.price);
var right = _compareMinPrice ? y.priceCl.Min(p => p.price) : y.priceCl.Max(p => p.price);
return left.CompareTo(right);
}
}
You can use the custom comparer in OrderBy as shown below.
// Sort by minimum price
var ascending = productLists.ProductDet.OrderBy(x => x, new ProductDetailsComparer(true)).ToList();
// Sort by maximum price
var descending = productLists.ProductDet.OrderBy(x => x, new ProductDetailsComparer(false)).ToList();
The above is just a sample. You can write a custom comparer suiting your requirements.
Upvotes: 0
Reputation: 9772
It is just simpler:
sorted_ProductDet_List = prdList.ProductDet
.OrderBy(prDet => prDet.sortPrice)
.ToList());
Then you'll have to add a Property sortPrice
to priceDetail which returns the relevant price used as sort criterium.
The lambda inside OrderBy
works on a single element of the original List (List) and specifies the variable/property/etc (probably from any nested class or method) the sorting is based on.
Upvotes: 2