How do you sort a class based on the property of its child class which is a collection? I'm doing a product and bid project where some products won't have bids and some will have bids. Here's what I've been trying but the problem is it gives me an "At least one object must implement IComparable" exception.
EDIT
The goal is to sort the products based on which of them has the highest or lowest bid.
Ascending Sort Example
|---------------------|------------------|
| Product | Most Recent Bid |
|---------------------|------------------|
| 1 | $100 |
|---------------------|------------------|
|---------------------|------------------|
| 2 | $150 |
|---------------------|------------------|
|---------------------|------------------|
| 3 | $175 |
|---------------------|------------------|
My Solution
productList = Sort == true ?
productList.OrderBy(x => x.Bids.OrderByDescending(y => y.BidAmount)) :
productList.OrderBy(x => x.Bids.OrderBy(y => y.BidAmount));
Product Class
public class Product
{
[Key]
public Guid ProductId { get; set; }
[MaxLength(30)]
public string ProductName { get; set; }
[MaxLength(200)]
[Required]
public string ProductDescription { get; set; }
[Required]
public string ImgUrl { get; set; }
[Required]
public DateTime ExpiryDate { get; set; }
[Required]
public DateTime UploadDate { get; set; }
public ICollection<Bid> Bids { get; set; }
}
Bid Class
public class Bid
{
[Key]
public Guid BidId { get; set; }
[Required]
public decimal BidAmount { get; set; }
[Required]
public DateTime BidDate { get; set; }
[Required]
[ForeignKey("Product")]
public Guid ProductId { get; set; }
public Product Product { get; set; }
[Required]
[ForeignKey("User")]
public Guid UserId { get; set; }
public User User { get; set; }
}
I have tried using solutions from both this and this but none cover the collection property use case.