C#列表分组和分配值 [英] C# List grouping and assigning a value

查看:398
本文介绍了C#列表分组和分配值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个订单列表.此列表包含同一项目的多个订单,请参见下表.

I have a list of Orders. This list contains multiple orders for the same item, see the table below.

然后,我想为每个相同(即ABC)的项目分配相同的块ID.因此,ABC的块ID为1&每个GHJ的块ID都为2,以此类推.这样做的最佳方法是什么?

I then want to assign each item that is the same (i.e. ABC) the same block ID. So ABC would have a block ID of 1 & each GHJ would have a block ID of 2 etc. What is the best way of doing this?

当前,我通过Order ID对列表进行排序,然后进行for循环,并检查当前Order ID是否等于下一个Order ID(如果这样),则将两个相同的块ID分配给该ID.是否有使用linq或任何其他方法执行此操作的更好方法?

Currently I order the list by Order ID and then have a for loop and check if the current Order ID is equal to the next Order ID if so assign the two the same block ID. Is there a better way of doing this using linq or any other approach?

Order ID             Block ID

ABC 
ABC
ABC
GHJ
GHJ
GHJ
MNO
MNO

推荐答案

在这种情况下,始终取决于更好对您意味着什么.

Always depends of what better means for you in this context.

有很多可能的方法可以解决这个琐碎的问题.
在我的头顶上,我想到了:

There are a bunch of possible solutions to this trivial problem.
On top of my head, I could think of:

var blockId = 1;
foreach(var grp in yourOrders.GroupBy(o => o.OrderId))
{
    foreach(var order in grp)
    {
        order.BlockId = blockId;
    }
    blockId++;
}

或(是更多"linqy" ):

foreach(var t in yourOrders.GroupBy(o => o.OrderId).Zip(Enumerable.Range(1, Int32.MaxValue), (grp, bid) => new {grp, bid}))
{
    foreach(var order in t.grp)
    {
        order.BlockId = t.bid;
    }
}

或(您仍然可以遵循该代码吗?):

or (can you still follow the code?):

var orders = yourOrders.GroupBy(o => o.OrderId)
                       .Zip(Enumerable.Range(1, Int16.MaxValue), (grp, id) => new {orders = grp, id})
                       .SelectMany(grp => grp.orders, (grp, order) => new {order, grp.id});
foreach(var item in orders)
{
    item.order.BlockId = item.id;
}

或(可能最接近简单的for循环):

or (probably the closest to a simple for loop):

Order prev = null;
blockId = 1;
foreach (var order in yourOrders.OrderBy(o => o.OrderId))
{
    order.BlockId = (prev == null || prev.OrderId == order.OrderId) ?
                    blockId :
                    ++blockId;
    prev = order;
}

Linq?是的.
比简单循环好吗?嗯......

Linq? Yes.
Better than a simple loop? Uhmmmm....

使用Linq不会神奇地使您的代码更好 .当然,它可以使它通常更具声明性/可读性/更快(就懒惰的评估而言),但是可以肯定的是,如果您尝试强制使用Linq仅仅是因为您可以使其他必要的命令式循环不可读 LINQ.

Using Linq will not magically make your code better. Surely, it can make it often more declarative/readable/faster (in terms of lazy evaluation), but sure enough you can make otherwise fine imperative loops unreadable if you try to force the use of Linq just because Linq.

作为旁注:
如果您想获得有关工作代码的反馈,可以在 codereview.stackexchange.com

As a side note:
if you want to have feedback on working code, you can ask at codereview.stackexchange.com

这篇关于C#列表分组和分配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆