Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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));
    }
}
like image 758
android_beginner Avatar asked Jul 05 '18 14:07

android_beginner


1 Answers

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();
like image 94
Bob K Avatar answered Oct 17 '22 03:10

Bob K