使用LINQ查找价格最便宜的产品?

编程入门 行业动态 更新时间:2024-10-11 01:20:20
本文介绍了使用LINQ查找价格最便宜的产品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在学习LINQ,我想从以下列表中找到最便宜的产品:

Im learning LINQ and I want to find the cheapest product from the following list:

List<Product> products = new List<Product> { new Product {Name = "Kayak", Price = 275M, ID=1}, new Product {Name = "Lifejacket", Price = 48.95M, ID=2}, new Product {Name = "Soccer ball", Price = 19.50M, ID=3}, };

我想出了以下几点,但是以某种方式,这似乎不是最好的方法:

I have come up with the following but somehow it feels like it is not the best way to do it:

var cheapest = products.Find(p => p.Price == products.Min(m => m.Price));

您能告诉我实现此目标的正确方法吗?

can you show me the right way to achieve this.

推荐答案

您应使用MinBy:

public static TSource MinBy<TSource>( this IEnumerable<TSource> source, Func<TSource, IComparable> projectionToComparable ) { using (var e = source.GetEnumerator()) { if (!e.MoveNext()) { throw new InvalidOperationException("Sequence is empty."); } TSource min = e.Current; IComparable minProjection = projectionToComparable(e.Current); while (e.MoveNext()) { IComparable currentProjection = projectionToComparable(e.Current); if (currentProjection.CompareTo(minProjection) < 0) { min = e.Current; minProjection = currentProjection; } } return min; } }

只需将此作为方法添加到public static类(EnumerableExtensions?)中即可.

Just add this as a method in a public static class (EnumerableExtensions?).

现在你可以说

var cheapest = products.MinBy(x => x.Price);

更多推荐

使用LINQ查找价格最便宜的产品?

本文发布于:2023-11-30 06:19:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648998.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最便宜   价格   产品   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!