使用 Linq 查询表达式但不使用 Fluent Syntax 通过 GroupBy 复制结果
Duplicate results with GroupBy using Linq Query Expression but not using Fluent Syntax
具有以下 Linq Fluent Expression:
按代码分组如下:
var list2 = trains.GroupBy(t => t.Country.ToUpper(),
t => t.Carriages,
(train, carriages) => new
{
Country = train,
TotalCarriages = carriages.Count(),
SumCarriage = carriages.SelectMany(c=>c).Sum(l=>l.Length)
}).ToList();
输出:
如果我尝试将 fluent 翻译成 linq q 表达式,尽管我在 groupBy:
中使用 Country.ToUpper() 但我有重复值
var query = (from t in trains
group t by new {Country = t.Country.ToUpper(), t.Carriages}
into g
select new
{
Country = g.Key.Country,
TotalCarriage = g.Key.Carriages.Count,
SumCarriage = g.Key.Carriages.Sum(c => c.Length)
}).ToList();
我无法解释为什么会这样。
当您使用方法语法时,您并没有根据两个不同的值进行分组,而是根据 仅 国家/地区进行分组并将所有元素转换为 Carriages
。如果您想使用查询语法来执行此操作,则语法为:
var query = (from t in trains
group t.Carriages by t.Country.ToUpper()
into g
select new
{
Country = g.Key,
TotalCarriages = g.Count(),
SumCarriage = g.SelectMany(c => c).Sum(l => l.Length)
}).ToList();
具有以下 Linq Fluent Expression: 按代码分组如下:
var list2 = trains.GroupBy(t => t.Country.ToUpper(),
t => t.Carriages,
(train, carriages) => new
{
Country = train,
TotalCarriages = carriages.Count(),
SumCarriage = carriages.SelectMany(c=>c).Sum(l=>l.Length)
}).ToList();
输出:
如果我尝试将 fluent 翻译成 linq q 表达式,尽管我在 groupBy:
中使用 Country.ToUpper() 但我有重复值 var query = (from t in trains
group t by new {Country = t.Country.ToUpper(), t.Carriages}
into g
select new
{
Country = g.Key.Country,
TotalCarriage = g.Key.Carriages.Count,
SumCarriage = g.Key.Carriages.Sum(c => c.Length)
}).ToList();
我无法解释为什么会这样。
当您使用方法语法时,您并没有根据两个不同的值进行分组,而是根据 仅 国家/地区进行分组并将所有元素转换为 Carriages
。如果您想使用查询语法来执行此操作,则语法为:
var query = (from t in trains
group t.Carriages by t.Country.ToUpper()
into g
select new
{
Country = g.Key,
TotalCarriages = g.Count(),
SumCarriage = g.SelectMany(c => c).Sum(l => l.Length)
}).ToList();