LambB表达式中的GroupBy

from x in myCollection group x by x.Id into y select new { Id = y.Key, Quantity = y.Sum(x => x.Quantity) }; 

你如何将上面的内容写成lambda表达式? 我被困在group into

查询连续(select … into和group … into,但不是 join … into)等同于只拆分查询表达式。 所以我想把你的例子想象成:

 var tmp = from x in myCollection group x by x.Id; var result = from y in tmp select new { Id = y.Key, Quantity = y.Sum(x => x.Quantity) }; 

将它们更改为点符号:

 var tmp = myCollection.GroupBy(x => x.Id); var result = tmp.Select(y => new { Id = y.Key, Quantity = y.Sum(x => x.Quantity) }); 

然后你可以把它们组合起来:

 var tmp = myCollection.GroupBy(x => x.Id) .Select(y => new { Id = y.Key, Quantity = y.Sum(x => x.Quantity) }); 

一旦你弄清楚C#编译器对查询表达式的作用,剩下的就相对简单:)

 myCollection.GroupBy(x => x.Id) .Select(y => new { Id = y.Key, Quantity = y.Sum(x => x.Quantity) }); 
 myCollection .GroupBy(x => x.Id) .Select(x => new { Id = x.Key, Quantity = x.Sum(y => x.Quantity }); 
  var mostFrequent = lstIn.Where(i => !string.IsNullOrEmpty(i)) .GroupBy(s => s) .OrderByDescending(g => g.Count()) .Select(s => s.Key) .FirstOrDefault(); 

因此,对于这里的大多数答案,每个人似乎都在处理从组的计数获得Id的简单对象,以及Key本身是group.Key。

虽然那可能是这个的主要用途。 没有真正满足我的需求。

对于我自己的情况,我基本上想要通过一些对象属性进行分组,然后从该组中获取特定对象。 这是一个示例代码。

 using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { Console.WriteLine("Hello World"); var response = new List(); var listOfStudents = new List(); // Insert some objects into listOfStudents object. listOfStudents.GroupBy(g => g.Class).ToList() .ForEach(g => response.Add(g.OrderByDescending(s => s.CreatedOn).Select(a => new ResponseClass { SName = a.StudentName, SAge = a.Age, SClass = a.Class, SCreatedOn = a.CreatedOn, RandomProperty = Guid.NewGuid().ToString() }) .First())); Console.WriteLine("This compiles and should work just fine"); } class Student { public string StudentName { get; set; } public int Age { get; set; } public string Class { get; set; } public DateTime CreatedOn { get; set; } } class ResponseClass { public string SName { get; set; } public int SAge { get; set; } public string SClass { get; set; } public DateTime SCreatedOn { get; set; } public string RandomProperty { get; set; } } } 

如果你更愿意使用foreach循环(我更喜欢lambda,因为我觉得它更容易阅读),但如果你这样做,你可以这样做。

 foreach (IGrouping groupedStudents in listOfStudents.GroupBy(g => g.Class)) { response.Add(groupedStudents.OrderByDescending(x => x.CreatedOn).Select(a => new ResponseClass { SName = a.StudentName, SAge = a.Age, SClass = a.Class, SCreatedOn = a.CreatedOn, RandomProperty = Guid.NewGuid().ToString() }).First()); } 

希望这有助于某人。 🙂