I have an IQueryable<Product> that needs to be sorted by Name. Each Product has an IQueryable<Category> that also needs to be sorted by Name. I’m having a hard time expressing this in Linq. I could loop through the products and sort each category list, but it seems messy. Hoping a Linq ninja has a smarter solution.
My Product class looks like:
public class Product {
public string Name { get; set; }
public IQueryable<Category> Categories { get; set; }
}
My Category class looks like:
public class Category {
public string Name { get; set; }
}
Currently, I’m doing this:
var myProducts = products.OrderBy(x => x.Name).Select(x => new Product {
Name = x.Name,
Categories = x.Categories(y => y.Name)
});
The trouble is, when using something like NHibernate, this creates new Product objects, essentially disconnecting the product from the NH session.
You don’t want to modify the
Productobject in any way that could affect persistence and you don’t want to create newProductinstances.So add this to
Productclass:And use
product.CategoriesOrderedByNameinstead when you need the sorted version in your UI code.Without this anyone using your class has no expectation that the
Categoryobjects are sorted in any way. With this you are being explicit in informing consumers of your class what to expect and that you intend to always return them in a sorted order. You can also useIOrderedEnumerable<>as the return type to make allow further sub-sorting usingThenBy().