求LINQ 查询一个list再查出字list
现有表二张
Product表
Pid PName
1 我是小风扇
2 我是电视机
ProductAttribute
PAid Pid AttributeName
1 1 颜色
2 1 颜色
ProductResult 逻辑实体字段为
public string Pid { get; set; }
public string PName { get; set; }
public List<ProductAttribute> list = new List<ProductAttribute>();
var query =from f in db.Product join j in db.ProductAttribute on f.Pid equels j.Pid
into temp from t in temp .DefaultIfEmpty()
select new ProductResult
{
PName=t.PName,
Pid=t.ID
//就这里我写纠结,我想通过Product .Pid == ProductAttribute.Pid这个列表保存起来给 list
}
就是想在每个product对象里面包含 List<ProductAttribute>求解答,
不知道怎么在第一个结果集再通过条件查询第二个结果集,求高人解答
[解决办法]
就是把所有在ProductAttribute 中与当前Product项的Pid相同的行选出来,放进List<>里?
[解决办法]
您试试这样?
List<ProductAttribute> list = from p in Product join a in ProductAttribute on p.Pid equals a.Pid into temp from t in temp.DefaultIfEmpty() select new ProductAttribute { Pid = p.Pid, PAid = t.Paid, AttributeName = t.AttributeName };
[解决办法]
有事要出去,晚上回来帮你想办法。
要返回实体,在new里构造也是一条可行的办法。
[解决办法]
直接:
var query = from p in db.Product select new { p.Pid, p.PName, Attributes = db.ProductAttribute.Where(pa => pa.Pid == p.Pid) };foreach(var item in query){ string a = item.PName; string b = item.Pid; List<ProductAttribute> list = item.Attributes.ToList();}
[解决办法]
建关系
var query = db.ProductInfos.ToList().Select(t=> new ProductResult { PName=t.PName, Pid=t.ID, list = t.ProductAttributeInfos };
[解决办法]
刚回家就看见你解决了问题,呵呵。恭喜,这也让我从中得到了锻炼。
我理解的你目标是这样:
假设有一个Product<Pid = 5>,然后把与之关联的所有Attribute作为一个内嵌的类,利用Product.Attributes直接访问到这组Attribute。
所以,我想在select 的new里,应该象之前我在4楼的回复一样,再有new或者子LINQ的查询,如同5楼的fangxinggood给出的答案一样。
而你在7楼的解决办法,正是因为LINQ to SQL返回的结果是IQueryable<>的,而不是LINQ to Objects的IEnumerable<>。而你之前声明的List<>是属于IEnumerable<>的,因此出现了错误。
这是我用Northwind做的一个模拟,其实List<>也是可以的,关键是接口类型的转换:
namespace LinqtoSql{ class Program { static void Main(string[] args) { NorthwindDataContext db = new NorthwindDataContext(); List<Result> entities = (from s in db.Suppliers join c in db.Customers on s.City equals c.City into temp from t in temp.DefaultIfEmpty() select new Result { SupplierName = s.CompanyName, Custs = db.Customers.Where(c => c.City == t.City).ToList() }).ToList<Result>(); foreach (Result r in entities) { Console.WriteLine("供应商<{0}>及其客户列表", r.SupplierName); foreach (Customers c in r.Custs) Console.WriteLine("\t{0}", c.ContactName); } } } class Result { public string SupplierName = string.Empty; public List<Customers> Custs = null; }
[解决办法]
[解决办法]