I want to write an elegant linq query to handle the following SAMPLE object model:
class Category { public string Name { get; set; } public IList<Product> Products { get; set;} } class Product { public string Title { get; set; } public IList<Photo> Photos { get; set; } } class Photo { public int Id { get; set; } }
I constructed the following query to get the Photo Id:
var query = from category in Factory.GetCategories() where category.Name == 'Cameras' select (from product in category.Products where product.Title == 'Sony' select (from photo in product.Photos select photo.Id) ); var v = query.ToList();
At the moment the query does not project correctly i have to add a FirstOrDefault() to each of the Sub Selects!:
var query = from category in Factory.GetCategories() where category.Name == 'Cameras' select (from product in category.Products where product.Title == 'Sony' select (from photo in product.Photos select photo.Id).FirstOrDefault() ).FirstOrDefault(); var v = query.ToList();
Is there a better way to do this? Ignoring the fact that we are not dealing with a database and PK’s/FK’s are not in play.
I really want to avoid writing a big for loop when i could do the same thing in a linq query:
foreach (var category in Factory.GetCategories()) { if (category.Name == 'Camera') { foreach (var product in category.Products) { if (product.Title == 'Sony') { foreach (var photo in product.Photos) { //get data int id = photo.Id; } } } } }
The actual implementation is more complex than this simple object model. I want to get the basic idea from this simple sample so i apply it to my real object model.
Cheers!
Do you just want the flattened ids?