如何在c#

时间:2015-11-08 14:40:51

标签: c# winforms linq

如何转换为LINQ:

from p in Product
join c in Catalog on c.Id equals p.CatalogId
join m in Manufacturer on m.Id equals p.ManufacturerId
where p.Active == 1
select new { Name = p.Name, CatalogId = p.CatalogId,
ManufacturerId =           p.ManufacturerId, CatalogName = c.Name,   
ManufacturerName = m.Name };

帮助!

3 个答案:

答案 0 :(得分:1)

不要尝试按字面翻译查询。在LINQ中,只要它们已经存在关系,就不需要加入实体,因为LINQ会自动使用该关系来加入实体:

假设您的Product具有Catalog属性,而该属性又具有Manufacturer属性,您可以编写LINQ而不加入像这样的连接:

from p in Product
where p.Active == 1
select new { 
  Name = p.Name, 
  CatalogId = p.CatalogId,
  ManufacturerId = p.ManufacturerId, 
  CatalogName = p.Catalog.Name,   
  ManufacturerName = p.Manufacturer.Name };

答案 1 :(得分:0)

解决方案是在第一次连接后构建临时结果并将其用作第二次连接中的第一个序列

var result = product.Where(p => p.Active == 1),  // 1st sequence
    .join(catalog,          // 2nd sequence
        p => p.CatalogId,   // selector from 1st sequence
        c => c.Id,          // selector from 2nd sequence
        (p, c) =>           // take the elements where the selector match
            new {ManufacturerId = p.ManufacturerId,
                 Name = p.Name,
                 CatalogId =  p.CatalogId,
                 CatalogName = c.Name})   // result is 1st sequence next join
    .Join(Manufacturer,                   // 2nd sequence 2nd join
        r => r.ManufacturerId,            // selector result 1st join
        m => m.Id,                        // selector 2nd sequence 2nd join
        (r, m) =>                         // two elements where the selectors match
            new {Name = r.Name,           // build the result object
                 CatalogId = r.CatalogId,
                 ManufacturerId = r.ManufacturerId,
                 CatalogName = r.CatalogName,
                 ManumfacturerName = r.Name});

答案 2 :(得分:-1)

一块蛋糕^^

只需调用IQueryable的ToString()方法,就会返回SQL Representation。

var query = from p in Product
            join c in Catalog on c.Id equals p.CatalogId
            join m in Manufacturer on m.Id equals p.ManufacturerId
            where p.Active == 1;
string sqlQuery = query.ToString(); //SQL Query Saved Here