我希望我能很好地解释我的情况,以便有所帮助。
基本上,我有一个由ItemRows组成的列表(ItemRows),如下所示
ItemRows
public string ItemId { get; set; }
public string ItemDate { get; set; }
public string ItemPrice { get; set; }目前,我处于一个foreach循环中,它在每次迭代中将当前变量传递给另一个函数。然而,当我超过价格时,我只想超过每个ItemDate的最高价格。
foreach item in ItemList
{
AnotherFunction(ItemId, ItemDate, MaxPriceByDate);
}所以如果我有以下4行数据.
123, 01/01/2015, $15
234, 01/01/2015, $20
345, 01/02/2015, $10
456, 01/02/2015, $5下面是我希望循环传递信息的方式:
first iteration: 123, 01/01/2015, $20
second iteration: 234, 01/01/2015, $20
third iteration: 345, 01/02/2015, $10
fourth iteration: 456, 01/02/2015, $10基本上,我在寻找关于如何从foreach循环使用的列表中选择美元金额的帮助,但我只希望它在每次迭代中按日期从所述列表中选择最高金额。
我希望这是有意义的,我感谢你的帮助!
发布于 2015-12-14 15:36:11
foreach(var item in ItemList)
{
AnotherFunction(item.ItemId, item.ItemDate, ItemList.Where(x => x.ItemDate == item.ItemDate)
.OrderByDesc(z => Convert.ToInt32(z.ItemPrice.Replace("$", "")))
.First().ItemPrice);
}发布于 2015-12-14 15:36:08
您可能希望按ItemDate属性进行分组,并对此进行稍微不同的处理。例如。
var grouped = (from r in rows
group r by r.ItemDate into g
select new { Date = g.Key, MaxPrice = g.Max(gg=>gg.ItemPrice)
Items = g})这将为您提供一个结构,其中每个元素都有一个日期、该日期的MaxPrice和属于该日期的项。通过在循环中进行一些小的修改,您可以将其适应到当前的结构中。
编辑:正如在另一个答案中所指出的,如果价格是字符串的,或者日期属性是相同的,那么您可能必须将价格转换成某种数字格式。在进入这个逻辑之前,我建议对字符串进行日期和数字的转换。
发布于 2015-12-14 15:36:59
如果您所要求的只是MaxPricePerDate,则可以使用以下linq函数:
int nMaxPrice = ItemList.Where(i => i.ItemDate == item.ItemDate
.Max(i => Convert.ToInt32(i.ItemPrice));此外,如果字符串确实包含$符号,则需要像i.ItemPrice.Replace("$", "");一样先剥离
需要Convert调用才能将字符串转换为int,但是如果字符串格式不正确,则会引发异常,这是很危险的。也考虑一下Int32.TryParse();
https://stackoverflow.com/questions/34270678
复制相似问题