2014-01-20 24 views
2

我有一个价格矩阵列表,我存储的宽度,长度和价格的项目。我想从输入宽度和长度中找到最大的宽度和高度。例如,比方说,如何使用LINQ从列表<Price>获取最接近的数字?

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作为宽度= 30高度= 13的结果?以及如果宽度= 40和高度= 16如何返回空值?

+0

请确切地说明H en W.的顺序。发布该构造函数的第一行。 –

+0

@HenkHolterman:我只想知道背后的逻辑,所以这就是为什么我没有在我的问题中写入构造函数。 –

+0

W = 10,H = 26应该返回什么?而对于W = 10,H = 10? –

回答

1

这应该为你做它:

// 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(); 
+0

谢谢..它只是我想要的方式。 –

+1

该解决方案有可能返回尺寸不佳的解决方案。比如说,你有两个矩形 - 5 x 1,000和6 x 7 - 如果你正在寻找一个大于4 x 4的矩形,那么5 x 1,000会被返回,或许6 x 7会更好比赛。 'orderby'行可能更好地表示为'orderby item.width * item.height',因为这将返回最接近的匹配大小。 – Enigmativity

+0

@Enigmativity这很疯狂,你只是通过查看我的代码来解决这个问题吗?惊人。 –

相关问题