如何在 LINQ 中为每个组分配一个自动递增的 ID?
How can I assign an auto-incrementing ID per group in LINQ?
我想按名称和数量对我的数据进行分组,返回的每个组都必须有一个唯一的 ID,该 ID 在数据中按组递增。
这是相关的代码:
return JsonConvert.SerializeObject(
data.GroupBy(x=> new {x.Name, x.Amount})
.Where(gp => gp.Count() > 1)
.Select(
gp =>
new Group
{
GroupData = gp.Select(el => new GroupItem
{
Name = el.Name,
Amount = el.Amount,
GroupId = <missing>
})
}));
我发现了几个关于为组中的每一行添加增量 ID 的问题,每个组都会重置,但是我希望组是这样的:
Group = {"bob", 145.20, 1},
{"bob", 145.20, 1},
Group = {"steve", 120.00, 2},
{"steve", 120.00, 2}..... etc
我找到的唯一示例在 SQL 中,而我需要在 C# 中为 LINQ 使用此示例。
您也可以使用传递索引的 Select 重载:
return JsonConvert.SerializeObject(
data.GroupBy(x=> new {x.Name, x.Amount})
.Where(gp => gp.Count() > 1)
.Select((gp, idx) =>
new Group
{
GroupData = gp.Select(el => new GroupItem
{
Name = el.Name,
Amount = el.Amount,
GroupId = idx
})
}));
我想按名称和数量对我的数据进行分组,返回的每个组都必须有一个唯一的 ID,该 ID 在数据中按组递增。
这是相关的代码:
return JsonConvert.SerializeObject(
data.GroupBy(x=> new {x.Name, x.Amount})
.Where(gp => gp.Count() > 1)
.Select(
gp =>
new Group
{
GroupData = gp.Select(el => new GroupItem
{
Name = el.Name,
Amount = el.Amount,
GroupId = <missing>
})
}));
我发现了几个关于为组中的每一行添加增量 ID 的问题,每个组都会重置,但是我希望组是这样的:
Group = {"bob", 145.20, 1},
{"bob", 145.20, 1},
Group = {"steve", 120.00, 2},
{"steve", 120.00, 2}..... etc
我找到的唯一示例在 SQL 中,而我需要在 C# 中为 LINQ 使用此示例。
您也可以使用传递索引的 Select 重载:
return JsonConvert.SerializeObject(
data.GroupBy(x=> new {x.Name, x.Amount})
.Where(gp => gp.Count() > 1)
.Select((gp, idx) =>
new Group
{
GroupData = gp.Select(el => new GroupItem
{
Name = el.Name,
Amount = el.Amount,
GroupId = idx
})
}));