我想编写一个优雅的linq查询来处理以下SAMPLE对象模型:
class Category { public string Name { get; set; } public IListProducts { get; set;} } class Product { public string Title { get; set; } public IList Photos { get; set; } } class Photo { public int Id { get; set; } }
我构造了以下查询来获取照片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();
在查询没有正确投影的那一刻,我必须为每个Sub Selects添加FirstOrDefault()!:
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();
有一个更好的方法吗?忽略我们没有处理数据库和PK/FK的事实并没有发挥作用.
当我在linq查询中做同样的事情时,我真的想避免编写一个大的for循环:
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; } } } } }
实际的实现比这个简单的对象模型更复杂.我想从这个简单的样本中得到基本的想法,所以我将它应用到我的真实对象模型.
干杯!
你只想要扁平的ids吗?
var query = from category in Factory.GetCategories() where category.Name == "Cameras" from product in category.Products where product.Title == "Sony" from photo in product.Photos select photo.Id;