c# - 如何使用 LINQ 从 List<Price> 中获取最接近的数字?

标签 c# linq list numbers

我有一个价格矩阵列表,其中存储了商品的宽度、长度和价格。我想从输入的宽度和长度中找到最大的宽度和高度。例如,假设,

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();

关于c# - 如何使用 LINQ 从 List<Price> 中获取最接近的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21228440/

相关文章:

list - 跟踪序言代码

c# - 不使用 Azure 客户端 SDK 连接到 IoT 中心

c# - JSON 序列化器 - 当前端缺少设置为 false 的 bool 值时

python - 对 Python 列表中的每个元素执行字符串操作

python - python 对象列表,每个对象都有自己的数组字典。附加到一个附加到所有

c# - 使用自定义方法构造 AndAlso/OrElse LINQ 表达式

c# - 跨多个项目重用数据库访问以确保更新时不会破坏任何项目的最佳方法是什么?

c# - MVC按钮点击调用POST Action方法

c# - 在 linq 查询中设置和使用值

c# - 使用 linq 与 xmlDocument 从 XML 字符串中提取数据