使用 LINQ 在列表中进行 Groupby 列表

发布于 2024-10-31 12:30:53 字数 563 浏览 1 评论 0原文

我有两个类:

class Customer
{
    public string Name { get; set; }
    public string ZipCode { get; set; }
    public List<Order> OrderList { get; set; }
}

class Order
{
    public string OrderNumber { get; set; }
}

使用 LINQ,我想按邮政编码获取订单组列表。如果邮政编码“12121”有 10 个客户,每个客户有 2 个订单,那么它应该只返回一个包含 20 个订单列表的邮政编码。

我正在尝试这样做,但无法弄清楚出了什么问题,

var orders = br.CustOrderList
.Select(r => new
{
    r.ZipCode,
    r.Name,
    r.OrderList
})
.GroupBy(x => new { x.ZipCode, x.OrderList}); 

有什么帮助吗?

I have two classes:

class Customer
{
    public string Name { get; set; }
    public string ZipCode { get; set; }
    public List<Order> OrderList { get; set; }
}

class Order
{
    public string OrderNumber { get; set; }
}

Using LINQ, i want to get list of Orders group by ZipCode. If Zipcode "12121" has 10 customers and each has 2 orders then it should return me only one Zipcode with the list of 20 orders.

I am trying to do it like this but not able to figure out whats wrong

var orders = br.CustOrderList
.Select(r => new
{
    r.ZipCode,
    r.Name,
    r.OrderList
})
.GroupBy(x => new { x.ZipCode, x.OrderList}); 

Any help please?

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

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

发布评论

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

评论(2

弃爱 2024-11-07 12:30:53

这应该做你想要的:

var orders = br.CustOrderList
    .GroupBy(x => x.ZipCode)
    .Select(g => new
    {
        ZipCode = g.Key,
        Orders = g.SelectMany(x => x.OrderList)
    });

This should do what you want:

var orders = br.CustOrderList
    .GroupBy(x => x.ZipCode)
    .Select(g => new
    {
        ZipCode = g.Key,
        Orders = g.SelectMany(x => x.OrderList)
    });
飘过的浮云 2024-11-07 12:30:53
var orders = br.CustOrderList
.Select(r => new
{
    r.ZipCode,
    r.Name,
    r.OrderList
})
.GroupBy(x => x.ZipCode); 

您只想按邮政编码分组,所以只需按邮政编码分组

啊是的,只需尝试即可

var order = br.CustOrderList
              .GroupBy(x = x.ZipCode);

,无需从列表中选择新项目

var orders = br.CustOrderList
.Select(r => new
{
    r.ZipCode,
    r.Name,
    r.OrderList
})
.GroupBy(x => x.ZipCode); 

You just want to group by the ZipCode so just group by that

Ah yea just try

var order = br.CustOrderList
              .GroupBy(x = x.ZipCode);

No need to select new items out of the list

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