GroupBy使用Linq查询表达式但不使用Fluent语法重复结果

时间:2015-03-02 15:15:41

标签: c# .net linq linq-to-objects

拥有以下Linq流利表达: 按代码分组如下:

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();

输出:

enter image description here

如果我试着将流利翻译成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();

enter image description here

我无法解释为什么会这样。

1 个答案:

答案 0 :(得分:1)

当您使用方法语法时,您没有对两个不同的值进行分组,而是在国家/地区进行分组,并将所有元素转换为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();