2010-06-23 142 views

回答

39

查询延续(SELECT ... 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#编译器使用查询表达式,其余部分相对简单:)

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

您应该添加一些文字说明此答案的作用以及为什么它提供了解决方案的具体问题。代码转储很少用于其他人。 – 2016-02-08 00:54:44

-1

因此,对于这里的大多数答案,每个人似乎都在处理从组的计数中获取Id的简单对象,以及作为group.Key的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<ResponseClass>(); 
      var listOfStudents = new List<Student>(); 
      // 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循环(我喜欢的λ,因为我觉得它更容易阅读),但是如果你这样做,你能做到这一点,像这样。

希望这可以帮助别人。 :)