C# 具有聚合和分组依据的LINQ查询
我有以下SQL查询C# 具有聚合和分组依据的LINQ查询,c#,linq,entity-framework,C#,Linq,Entity Framework,我有以下SQL查询 select seaMake AS Make, seaModel AS Model, COUNT(*) AS [Count], MIN(seaPrice) AS [From], MIN(seaCapId) AS [CapId] from tblSearch where seaPrice >= 2000 and seaPrice <= 7000 group by seaMake, seaMo
select seaMake AS Make,
seaModel AS Model,
COUNT(*) AS [Count],
MIN(seaPrice) AS [From],
MIN(seaCapId) AS [CapId]
from tblSearch
where seaPrice >= 2000
and seaPrice <= 7000
group by seaMake, seaModel
order by seaMake, seaModel
选择seaMake作为Make,
seaModel作为模型,
计数(*)为[计数],
最低(海运价格)为[自],
最小值(seacpid)为[CapId]
来自tblSearch
其中海运价格>=2000
而seaPrice=2000
&&s.seaPrice x.seaMake),
PriceFrom=g.Min(s.seaPrice)
};
我哪里出错了?这应该是SQL的简单翻译:
from s in db.tblSearches
where
s.seaPrice >= 2000 &&
s.seaPrice <= 7000
group s by new {s.seaMake, s.seaModel} into g
orderby g.Key
select new
{
Make = g.Key.seaMake,
Model = g.Key.seaModel,
Count = g.Count(),
From = g.Min(x => x.seaPrice),
CapId = g.Min(x => x.seaCapId)
}
来自数据库中的s.tblsearch
哪里
s、 海运价格>=2000&&
s、 seaPrice x.seaPrice),
CapId=g.Min(x=>x.seacpid)
}
当分组到g时,您将该集合转换为IEnumerable>,因此当前范围内的集合为g
。因此,以下内容是有效的
from s in db.tblSearches
where s.seaPrice >= 2000
&& s.seaPrice <= 7000
orderby s.seaMake
group s by s.seaMake into g // the collection is now IEnumerable<IGrouping<TypeOfSeaMake, TypeofS>>
select new {
make = g.Key, // this was populated by s.seaMake
model = g.First().seaModel, // get the first item in the collection
count = g.Max(x => x.seaMake), // get the max value from the collection
PriceFrom = g.Min(x => x.seaPrice), // get the min price from the collection
};
来自数据库中的s.tblsearch
其中s.seaPrice>=2000
&&s.seaPrice x.seaMake),//从集合中获取最大值
PriceFrom=g.Min(x=>x.seaPrice),//从集合中获取最小价格
};
现在,每个分组将返回一个项目如果您取出orderby和GroupBy子句,您可以选择make/model吗?是的,因为分组将使用var g,而var g与var不同,因此我猜您可以使用
g.Key
访问seaMake
。试试看,让我知道它是否适合你。
from s in db.tblSearches
where s.seaPrice >= 2000
&& s.seaPrice <= 7000
orderby s.seaMake
group s by s.seaMake into g // the collection is now IEnumerable<IGrouping<TypeOfSeaMake, TypeofS>>
select new {
make = g.Key, // this was populated by s.seaMake
model = g.First().seaModel, // get the first item in the collection
count = g.Max(x => x.seaMake), // get the max value from the collection
PriceFrom = g.Min(x => x.seaPrice), // get the min price from the collection
};