我有一个价格矩阵列表,我在其中存储商品的宽度,长度和价格。我想从输入的宽度和长度中找到最大的宽度和高度。例如,假设
Public Class ItemPrice
{
public int id{ get; set; }
public string item{ get; set; }
public int width{ get; set; }
public int height{ get; set; }
public decimal price{ get; set; }
}
List<ItemPrice> itemorder = new List<ItemPrice>();
itemorder.Add(new ItemPrice(1,"A",24,12,$12.24));
itemorder.Add(new ItemPrice(2,"A",24,14,$16.24));
itemorder.Add(new ItemPrice(3,"A",36,12,,$18.24));
itemorder.Add(new ItemPrice(4,"A",36,14,$21.24));
这意味着它看起来像
24 36
--------------------
12 | $12.24 $18.24
14 | $16.24 $21.24
我如何找到ItemPrice id 4作为width = 30和height = 13的结果?如果宽度= 40和高度= 16,我如何返回空值?
这应该为您做到:
// Change these as needed
int orderWidth = 1;
int orderHeight = 1;
var bestMatch = (from item in itemorder
where item.width >= orderWidth
where item.height >= orderHeight
orderby item.width * item.height
select item).FirstOrDefault();
此LINQ查询将所有大小小于订购大小的项目过滤掉。然后,它将其余项目按升序排序。最后,它选择第一个项目(==最小项目)或null。
编辑
这是一个基于每个项目边的总和的更新解决方案。
int orderWidth = 4;
int orderHeight = 4;
int orderSum = orderWidth + orderHeight;
var bestMatch = (from item in itemorder
where item.width >= orderWidth
where item.height >= orderHeight
let itemSum = item.width + item.height
let difference = Math.Abs(orderSum - itemSum)
orderby difference
select item).FirstOrDefault();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句