.OrderBy() / .OrderByDescending() with .FirstOrDefault()/.First()

11,386

I don't see a filter for the user and you are ordering by user. Try this.

return List(spec).Where(x => x.User == "James")
                 .OrderByDescending(y => y.ArrivalDate)
                 .FirstOrDefault();
Share:
11,386

Related videos on Youtube

android_beginner
Author by

android_beginner

Updated on September 15, 2022

Comments

  • android_beginner
    android_beginner about 1 year

    I have list of results from table named "product".

    Id      User    ProductName     ArrivalDate
    ----    -----   ------------    ------------
    1       James   Shoes           05/07/2016
    2       Jenny   TShirt          05/01/2018
    3       James   Pants           13/05/2017
    

    i would like to sort the result by descending order based on ArrivalDate where User is "James", which mean it should return to me the third row result. However, if i do as below:

    return List(spec).OrderByDescending(x=>x.ArrivalDate).FirstOrDefault();
    

    the result i got is still the first one, appereciate if anyone could guide on this. Below is the sample code:

    public class EfRepository<T> : IRepository<T>, IAsyncRepository<T> where T : BaseEntity
    {
        public T GetSingleBySpec(ISpecification<T> spec)
        {
            return List(spec).FirstOrDefault();
        }
    }
    
    public class ProductSpecification : BaseSpecification<NewProducts>
    {
        public ProductSpecification(string User)
        : base(b => b.User == User) //User = James
        {
    
        }
    }
    
    public class ProductService : IProductService
    {
        public void getOrderProductDetails
        {
            var data = _productRepository.GetSingleBySpec(new ProductSpecification(user));
        }
    }
    
  • android_beginner
    android_beginner over 5 years
    Bob K, it is still the same