lambda 表达式中的 GroupBy

发布于 2024-09-06 09:58:44 字数 228 浏览 1 评论 0原文

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 部分。

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

How would you write the above as a lambda expression? I'm stuck on the group into part.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

鹿港小镇 2024-09-13 09:58:44

查询延续(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# 编译器对查询表达式的作用,其余的就相对简单了:)

Query continuations (select...into and group...into, but not join...into) are equivalent to just splitting up the query expression. So I like to think of your example as:

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

Change those into dot notation:

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

Then you could combine them back:

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

Once you work out what the C# compiler does with query expressions, the rest is relatively straightforward :)

っ左 2024-09-13 09:58:44
myCollection
    .GroupBy(x => x.Id)
    .Select(x => 
        new 
        { 
          Id = x.Key, 
          Quantity = x.Sum(y => x.Quantity
        });
myCollection
    .GroupBy(x => x.Id)
    .Select(x => 
        new 
        { 
          Id = x.Key, 
          Quantity = x.Sum(y => x.Quantity
        });
我还不会笑 2024-09-13 09:58:44
myCollection.GroupBy(x => x.Id)
            .Select(y => new {
                                 Id = y.Key,
                                 Quantity = y.Sum(x => x.Quantity)
                             });
myCollection.GroupBy(x => x.Id)
            .Select(y => new {
                                 Id = y.Key,
                                 Quantity = y.Sum(x => x.Quantity)
                             });
夏雨凉 2024-09-13 09:58:44
        var mostFrequent =
            lstIn.Where(i => !string.IsNullOrEmpty(i))
                 .GroupBy(s => s)
                 .OrderByDescending(g => g.Count())
                 .Select(s => s.Key)
                 .FirstOrDefault();
        var mostFrequent =
            lstIn.Where(i => !string.IsNullOrEmpty(i))
                 .GroupBy(s => s)
                 .OrderByDescending(g => g.Count())
                 .Select(s => s.Key)
                 .FirstOrDefault();
·深蓝 2024-09-13 09:58:44

因此,对于这里的大多数答案,每个人似乎都在处理从组的计数中获取一个简单的 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<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 循环(我更喜欢 lambda,因为我发现它更容易阅读),但如果你这样做,你可以这样做。

foreach (IGrouping<string, Student> 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());
            }

希望这对某人有帮助。 :)

So, for most of the answers here, everyone seems to be dealing with getting a simple object of Id made from count of the group, and the Key itself which is group.Key.

Although thats probably the main useage of this. Didn't really satisfy my needs.

For my own case, I basically wanted to group by some object property, then fetch a specific object from that group. Here's a sample code.

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; }
    }
}

If you would rather use a foreach loop (I prefer lambda as I find it easier to read), but if you do, you could do it like so.

foreach (IGrouping<string, Student> 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());
            }

Hope this helps someone. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文