【问题标题】:Using linq to find the cheapest item in a list thats greater than 0使用 linq 在大于 0 的列表中查找最便宜的项目
【发布时间】:2015-02-21 01:26:08
【问题描述】:

我面临排序列表的问题,我试图找到最便宜的值。排序不是问题,它返回的值是问题和我想要满足的条件。

基本上,我的结果集中可能有 0 个值,这是因为这些项目已被暂时搁置,因此它们没有值,但报价仍然到达。

想法是按总价值对结果进行排序,然后取出列表中理论上最便宜的第一项。

void Main()
{
    GetCheapest();
}

public void GetCheapest()
{
    List<Car> numbers = new List<Car>
    {
         new Car() { Type="dearest",    Total = 990 },
         new Car() { Type="",           Total = 570 },
         new Car() { Type="",           Total = 907 },
         new Car() { Type="cheapest",   Total = 0 },
         new Car() { Type="",           Total = 333 },
         new Car() { Type="",           Total = 435 },
         new Car() { Type="",           Total = 435 }
    };

    //order ascending
    IEnumerable<Car> query = numbers.OrderBy( q => q.Total );

    //set the cheapest to be the first index in the sorted IEnumerable
    var cheapest = query.First();

    //output the cheapest
    Console.Write( cheapest.Type + " - £" + cheapest.Total + ", Winning!!" );

    //new line
    Console.WriteLine( Environment.NewLine );

    //output each one
    foreach( Car q in query )
    {
        Console.WriteLine( q.Type + " - £" + q.Total );
    }
}


//Quote Object
public class Car
{
    public decimal Total { get; set; }
    public string Type { get; set; }
}

总结 我想遍历返回的列表,直到找到一个值大于 0 的索引。

给出的例子的答案是 333。

如果有人对此有更好的想法,我愿意尝试。

到目前为止,我已经查看了关于 SO 的这些问题,给出了答案:

use LINQ to find the product with the cheapest value?

Get object with minimum value using extension method min()

【问题讨论】:

  • 我很困惑......您发布的代码已经这样做了,对吧?您在寻找更好的方法吗?
  • @HaukurHaf 是的,它确实给出了最便宜的值,即 0,但 0 不是一个值,高于 0 的任何值都是最便宜的值。
  • 当然是的 :-) 然后我只需添加一个 where 语句以在订购前排除 0 的值,然后取第一个。编辑:就像下面 D Stanley 的回答一样。

标签: c# linq


【解决方案1】:

除非我错过了什么,否则就是:

numbers.Where(c => c.Total > 0)
       .OrderBy(c => c.Total)
       .First();

或链接到您现有的查询:

IEnumerable<Car> query = numbers.OrderBy( q => q.Total );

var cheapestCar = 
    query.Where(c => c.Total > 0)
         .First();

【讨论】:

  • 干净优雅,谢谢!我将保留 IEnumerable ,因为我想遍历以输出每个值以进行比较。
  • @KyleT 然后,如果您愿意,您可以直接链接到它——我已将其添加到我的答案中。
【解决方案2】:
int cheapest = numbers.Where(c=>c.Total > 0).Min(c=>c.Total);

将为您提供列表中大于 0 的最低价格。

where 子句从列表中删除总数

如果您宁愿拥有整个对象而不仅仅是价格,请使用

var cheapest = numbers.OrderBy(c=>c.Total).First(c=>c.Total > 0);

【讨论】:

  • 我认为 OP 想要相应的 Car 对象,而不是 Total 值。
  • 感谢您的回答!这也行得通,赞成你使用 min。
【解决方案3】:

如果您想找到一种方法来处理已排序的值列表:

IEnumerable<Car> query = numbers.OrderBy( q => q.Total );

跳过所有的0,然后取第一个元素:

var cheapest = query.SkipWhile(x => x == 0).First();

【讨论】:

  • @pquest 在我的回答中,我假设值已经排序。你可以看看我所做的编辑。
  • 值是 0 时不应该跳过,还是
  • @juharr 你是对的,这与我写的相反。我认为负值被排除在外,因为值代表价格。
猜你喜欢
  • 2022-01-11
  • 1970-01-01
  • 2019-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多