使用 linq 进行分组;但有条件的话
我很难理解如何对这些类的列表进行分组。
public class Order
{
public int OrderId { get; set; }
public long OrderClassId { get; set; }
public int OrderTypeId { get; set; }
public int OrderSubTypeId { get; set; }
public string OrderString { get; set; }
//.. other Order stuff not relevant to question
}
我理解的基本分组。它看起来像这样(假设 orders
是一个 List
):
var orderGroups = orders.GroupBy(x=>x.OrderClassId);
// Code to assign a unique OrderString to each group goes here
但是,具有相同 OrderClassId、OrderTypeId 为 123 且具有相同 OrderSubTypeId 的订单需要有不同的 OrderString 值。
这有点令人困惑,所以这里有一个示例:
var order1 = new Order
{
OrderId = 1,
OrderClassId = 8754,
OrderTypeId = 123,
OrderSubTypeId = 7156
};
var order2 = new Order
{
OrderId = 2,
OrderClassId = 8754,
OrderTypeId = 123,
OrderSubTypeId = 7156
};
var order3 = new Order
{
OrderId = 3,
OrderClassId = 8754,
OrderTypeId = 951,
OrderSubTypeId = 35144
};
通过我的分组,所有这些都将获得相同的 OrderString
。但我需要 order2
来获取不同的 OrderString
。
使用 linq 可以吗?或者我是否只需要迭代所有行并手动分离符合我的条件的行。
I am having trouble wrapping my head on how to group a list of these classes.
public class Order
{
public int OrderId { get; set; }
public long OrderClassId { get; set; }
public int OrderTypeId { get; set; }
public int OrderSubTypeId { get; set; }
public string OrderString { get; set; }
//.. other Order stuff not relevant to question
}
The basic grouping I understand. It looks like this (assume orders
is a List<Order>
):
var orderGroups = orders.GroupBy(x=>x.OrderClassId);
// Code to assign a unique OrderString to each group goes here
However, orders that have the same OrderClassId and have an OrderTypeId of 123 and have the same OrderSubTypeId need to have different OrderString values.
That is a bit confusing, so here is an example:
var order1 = new Order
{
OrderId = 1,
OrderClassId = 8754,
OrderTypeId = 123,
OrderSubTypeId = 7156
};
var order2 = new Order
{
OrderId = 2,
OrderClassId = 8754,
OrderTypeId = 123,
OrderSubTypeId = 7156
};
var order3 = new Order
{
OrderId = 3,
OrderClassId = 8754,
OrderTypeId = 951,
OrderSubTypeId = 35144
};
With my grouping, all of these would get the same OrderString
. But I need order2
to get a different OrderString
.
Is that possible using linq? Or am I just going to have to iterate all the rows and manually separate the ones that match my criteria.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用匿名类型,例如:
Use anonymous type, e.g.:
您可以在生成密钥时执行条件。
You can do conditions as you generate the keys.
我认为这就是你可以使用的(OrderId 是唯一的,对吧?):
I think this is what you could use (OrderId is unique, right?):
正如基里尔所说,只需使用
var orderGroups =orders.GroupBy(x => new { x.OrderClassId, x.OrderSubTypeId });
As Kirill says just use
var orderGroups = orders.GroupBy(x => new { x.OrderClassId, x.OrderSubTypeId });