I have two tables:
User {
PK: UserId
...
}
Product {
PK: ProductId,
FK: UserId
...
}
I have a list of ProductId
s 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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With