public class A
{
public int Price;
public int Available;
}
让我们以这个数据为例:
var items = new List<A>
{
new A { Price = 10, Available = 1000 },
new A { Price = 15, Available = 500 },
new A { Price = 20, Available = 2000 },
};
我的查询返回特定数量的平均价格,比如:
如果我请求100个,那么我的平均价格是10
如果我请求1200个,则前1000个按10元/个的价格购买,然后下一个200个按每个15元的价格购买等等。
我已经在C#中实现了这一点,但我正在尝试找出是否可以直接使用数据库迭代器中的LINQ来完成此操作。
我获取的数据已经按价格排序,但我不知道如何在不迭代的情况下解决这个问题。
编辑:
这是代码:
public static double PriceAtVolume(IEnumerable<A> Data, long Volume)
{
var PriceSum = 0.0;
var VolumeSum = 0L;
foreach (var D in Data)
{
if (D.Volume < Volume)
{
PriceSum += D.Price * D.Volume;
VolumeSum += D.Volume;
Volume -= D.Volume;
}
else
{
PriceSum += D.Price * Volume;
VolumeSum += Volume;
Volume = 0;
}
if (Volume == 0) break;
}
return PriceSum / VolumeSum;
}
测试代码如下:
var a = new List<A>
{
new A { Price = 10, Volume = 1000 },
new A { Price = 15, Volume = 500 },
new A { Price = 20, Volume = 2000 }
};
var P0 = PriceAtVolume(a, 100);
var P1 = PriceAtVolume(a, 1200);
说明:
我之前说过,我希望将其移动到LINQ以使用数据库迭代器,因此我想避免扫描整个数据并在计算答案时停止迭代。 数据已经按价格在数据库中排序。
{10, 1000}
不匹配。 - Maslow