Performance LINQ与Group、Join和Where Easy在SQL中不是在LINQ中?
我很难理解如何将SQL翻译成LINQ。我想做以下工作,但不知道如何让团队工作Performance LINQ与Group、Join和Where Easy在SQL中不是在LINQ中?,performance,linq,entity-framework,linq-to-sql,Performance,Linq,Entity Framework,Linq To Sql,我很难理解如何将SQL翻译成LINQ。我想做以下工作,但不知道如何让团队工作 var query = from s in Supplier join o in Offers on s.Supp_ID equals o.Supp_ID join p in Product on o.Prod_ID equals p.Prod_ID where s.City == "Chicago" group s by
var query = from s in Supplier
join o in Offers on s.Supp_ID equals o.Supp_ID
join p in Product on o.Prod_ID equals p.Prod_ID
where s.City == "Chicago"
group s by s.City into Results
select new { Name = Results.Name };
我只需要做一些简单的事情,比如显示这个简单查询的产品名称,group by如何处理连接和where?您没有提供类,所以我假设它们如下所示:
public class Supplier
{
public int SupplierID { get; set; }
public string SuppierName { get; set; }
public string City { get; set; }
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
}
public class Offer
{
public int SupplierID { get; set; }
public int ProductID { get; set; }
}
然后我添加了用于测试的数据:
它必须给出以下结果:
FirstCompany
SecondCompany您可以尝试以下方法:
var query = from s in Supplier
join o in Offers on s.Supp_ID equals o.Supp_ID
join p in Product on o.Prod_ID equals p.Prod_ID
where s.City == "Chicago"
group s
by new {s.City, s.Name} //added this
into Results
select new { Name = Results.Key.Name };
您可以按s.City
对s
(供应商)进行分组。其结果是i分组
。也就是说,在分组后,只有城市
和供应商
可以到达:对于每个城市,您可以得到其供应商的IEnumerable
(顺便说一句,这将乘以联接)
因为你也有一个条件,s.City==“Chicago”按城市分组是没有用的。只有一个城市。所以我想你不妨这样做:
from s in Supplier
join o in Offers on s.Supp_ID equals o.Supp_ID
join p in Product on o.Prod_ID equals p.Prod_ID
where s.City == "Chicago"
select new {
City = s.City.Name,
Supplier = s.Name,
Product = p.Name,
...
};
相当彻底。为什么不将结果数据添加到您的答案中?您是否可以使用导航属性,如
Supplier.Offers
和Offer.Products
?
foreach (string supplierName in result)
{
Console.WriteLine(supplierName);
}
var query = from s in Supplier
join o in Offers on s.Supp_ID equals o.Supp_ID
join p in Product on o.Prod_ID equals p.Prod_ID
where s.City == "Chicago"
group s
by new {s.City, s.Name} //added this
into Results
select new { Name = Results.Key.Name };
from s in Supplier
join o in Offers on s.Supp_ID equals o.Supp_ID
join p in Product on o.Prod_ID equals p.Prod_ID
where s.City == "Chicago"
select new {
City = s.City.Name,
Supplier = s.Name,
Product = p.Name,
...
};