Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort objects returned by EF according to a list of IDs?

I have two tables:

User {
    PK: UserId
    ...
}

Product {
    PK: ProductId, 
    FK: UserId
    ...
}

I have a list of ProductIds in random format. I do not want to sort the output result and I would like to include User data as well for each product Id.

The below code provides the data in sorted format. How can I avoid this sorting? I want the list of objects to be in the same order as our product list.

List<Tables.Product> tblProductList =
    repo.Products
        .Include("User")
        .Where(x => productIdList.Contains(x.ProductId))
        .ToList(); 
like image 486
Jyotish Singh Avatar asked Oct 18 '22 07:10

Jyotish Singh


1 Answers

I want the list of objects to be in the same order as our product list.

I assume by our product list you mean the productIdList variable used for filtering.

You cannot do that in LINQ to Entities, so you have to switch to LINQ to Objects and do the ordering in memory.

One way would be to use IndexOf method:

var tblProductList =
    repo.Products
        .Include("User")
        .Where(x => productIdList.Contains(x.ProductId))
        .AsEnumerable() // Switch to LINQ to Objects context
        .OrderBy(x => productIdList.IndexOf(x.ProductId))
        .ToList();

Another more performant method (when productIdList is big) could be to use intermediate dictionary:

var productsById =
    repo.Products
        .Include("User")
        .Where(x => productIdList.Contains(x.ProductId))
        .ToDictionary(x => x.ProductId);

var tblProductList = productIdList
    .Select(productId => productsById[productId])
    .ToList();
like image 78
Ivan Stoev Avatar answered Oct 21 '22 06:10

Ivan Stoev