List<SalesRecord> SalesRecords = new List<SalesRecord>();
while(sr.EndOfStrem)
{
SalesRecord Sale = new SalesRecord();
//assigns data to sale.pluid, sale,quantity, sale.subtotal
SalesRecords.Add(Sale);
}
foreach (SalesRecord _sale in SalesRecords)
{
foreach (SalesRecord _matchingSale in SalesRecords)
{
if (_sale.PLUId == _matchingSale.PLUId)
{
_sale.Quantity = _sale.Quantity + _matchingSale.Quantity;
_sale.Subtotal = _sale.Subtotal + _matchingSale.Subtotal;
//SalesRecords.Remove(_matchingSale);
}
}
}
Console.WriteLine(SalesRecords.ToList());
这只是输出:
Synchroniser.SalesRecord,
Synchroniser.SalesRecord,
Synchroniser.SalesRecord,
Synchroniser.SalesRecord,
Synchroniser.SalesRecord,
Synchroniser.SalesRecord
etc..etc..etcc
我想输出saleRecords的销售额?每条记录的ID,数量和小计?
我也已经删除了删除行。因为这会抛出错误:集合被修改:枚举操作可能无法执行。
我的逻辑错了吗? 我试图做的是
输入
PLUId Quantity Subtotal
1 4 4.00
2 2 8.50
3 7 3.90
1 3 3.00
所以最后我想要以下结果:
PLUId Quantity Subtotal
1 7 7.00
2 2 8.50
3 7 3.90
..请告知
答案 0 :(得分:1)
我建议使用Dictionary
,而不是将重复的项目添加到列表中,然后将其删除。
var SalesRecords = new Dictionary<int, SalesRecord>();
在while
循环中,您可以进行查找:
var currentPLUId = // get the PLUId for the current record
if (SalesRecords.ContainsKey(currentPLUId))
{
var sale = SalesRecords[currentPLUId];
// increase the quantity, subtotal fields
}
else
{
var sale = new SalesRecord();
// set the quantity, subtotal fields
SalesRecords.Add(currentPLUId, sale);
}
此外,您对Console.WriteLine(SalesRecords.ToList());
的调用会输出错误的数据,因为您不能只将整个列表传递给它,并希望它知道该如何处理。您可以具体告诉它显示哪些值:
foreach (var sale in SalesRecords)
Console.WriteLine(string.Concat(
sale.PLUId, " - " , sale.Quantity, " - ", sale.Subtotal);
或者您可以覆盖SalesRecord类中的ToString
以显示您想要的任何内容,然后执行以下操作:
foreach (var sale in SalesRecords)
Console.WriteLine(sale); // sale.ToString() is called
答案 1 :(得分:0)
如果您被允许使用LINQ,您可以将您的PLUId分组并在新集合中汇总数量和小计:
var qr = (from s1 in SalesRecords
group s1 by s1.PLUId into g
select new SalesRecord{
PLUId = g.Key ,
Quantity = g.Sum( m =>m.Quantity ) ,
Subtotal = g.Sum( m=> m.Subtotal) })
.ToList();
Console.WriteLine("PLUId Quantity Subtotal");
foreach (var s in qr)
Console.WriteLine("{0,7} {1,9} {2,9}",s.PLUId, s.Quantity, s.Subtotal);