Ordering a list based on child class which is a collection

Viewed 65

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.

1 Answers

Ordering the Bids based on amount is not throwing that error. The problem is x.Bids.OrderBy(...) returns a list of Bids so you are trying to order the Products based on a list of Bids. Since there is no way to compare a generic list to another, you need to be more specific.

If you want to order the products based on the number of bids you could use this

productList.OrderBy(x => x.Bids.Count());

Or if you want to order the products based on the total amount of the bids you could use this

productList.OrderBy(x => x.Bids.Sum(b => b.BidAmount));
Related