gpt4 book ai didi

c# - 如何使用 LINQ 在列表中生成重复项?

转载 作者:可可西里 更新时间:2023-11-01 08:42:53 25 4
gpt4 key购买 nike

这是我用过的 LINQ 查询

var result = (from price in inventoryDb.Pricing.AsNoTracking()               
where price.Quantity > 0m
select new
{
TagNo = price.TagNo,
SellingRate = price.SellingRate,
Quantity = price.Quantity
}).ToList();

根据 Quantity 值,我需要在列表中生成重复项。

输出:

result = [0]{TagNo="100", SellingRate=1500.00, Quantity=1}
[1]{TagNo="101", SellingRate=1600.00, Quantity=2}

预期结果:

result = [0]{TagNo="100", SellingRate=1500.00}
[1]{TagNo="101", SellingRate=1600.00}
[2]{TagNo="101", SellingRate=1600.00}

最佳答案

您可以使用Enumerable.SelectMany + Enumerable.Range:

var result = inventoryDb.Pricing.AsNoTracking()
.Where(p => p.Quantity > 0m)
.SelectMany(p => Enumerable.Range(0, p.Quantity)
.Select(i => new
{
TagNo = p.TagNo,
SellingRate = p.SellingRate
}))
.ToList();

如果您的 LINQ 提供程序(例如 Linq-To-Entities)不支持,最简单的方法是使用 Linq-To-Objects。为避免所有内容都加载到内存中,您应该在 Where 之后使用 AsEnumerable:

var result = inventoryDb.Pricing.AsNoTracking()
.Where(p => p.Quantity > 0m)
.AsEnumerable()
.SelectMany(p => Enumerable.Range(0, p.Quantity)
.Select(i => new
{
TagNo = p.TagNo,
SellingRate = p.SellingRate
}))
.ToList();

关于c# - 如何使用 LINQ 在列表中生成重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39914274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com