简体   繁体   English

如何使用LINQ获取最低值的项目?

[英]How to get the items with lowest value using LINQ?

I have below class -我有以下课程-

  public class Test
    {
        public string TestServerName;
        public string TestApplicationRunning;
        public bool IsAvailable;
        public long Counter;
    }

How to get the items with lowest counter value using LINQ?如何使用 LINQ 获取计数器值最低的项目?

Suppose lowest counter value is 0 in all items then LINQ should return all items with Counter value 0.There can be more then 1 items with counter value minimum.假设所有项目中的最低计数器值为 0,则 LINQ 应返回计数器值为 0 的所有项目。计数器值最小值可以多于 1 个项目。

You can use Min extension method and then filter source with the help of Where extension method:您可以使用Min扩展方法,然后Where扩展方法的帮助下过滤源:

var minValue = source.Min(x => x.Counter);
var result = source.Where(x => x.Counter == minValue).ToList();

Don't forget to include Systme.Linq namespace.不要忘记包含Systme.Linq命名空间。 BTW, with this approach, you will execute two queries to the source.顺便说一句,使用这种方法,您将对源执行两个查询。

You could also do :你也可以这样做:

source.GroupBy(x=>x.Counter)
      .OrderBy(x=>x.Key)
      .Take(1)
      .Select(x=>x).ToList();

though it's not as obvious as Fᴀʀhad's solution :)虽然它不像 Fᴀʀhad 的解决方案那么明显 :)

Try this example:试试这个例子:

List<Test> lstTests = new lstTests();
Test test1 = new Test();
Test test2 = new Test();
Test test3 = new Test();

test1.Counter = 3;
test2.Counter = 4;
test3.Counter = 3;

lstTests.Add(test1);
lstTests.Add(test2);
lstTests.Add(test3);


var valMin = lstTests.Min(m => m.Counter);
var results = source.Where(x => x.Counter == valMin).ToList();

OR或者

var result = source.Where(x => x.Counter == valMin).FirstOrDefault();

If u want the first occurance Use FirstOrDefault .如果你想要第一次出现,请使用FirstOrDefault

With below query you can find nth lowest value通过以下查询,您可以找到第 n 个最低值

int ix = 1;
var orderedSource  = source.OrderBy(i => i.counter).Select(y => new { rank =ix++ , value = y });

you pass any value instead of N to get nth lowest value您传递任何值而不是 N 以获得第 n 个最低值

int N = 4;
var  result  = orderedSource.Where(x=>x.rank == N).FirstOrDefault();
Test testValue = result.value; 

You can use the MinBy (or MaxBy ) extension method from MoreLinq .您可以使用MinBy (或MaxBy延伸,从方法MoreLinq

As from this issue , the min by functionality change to return IEnumerable of T (if to be more precise: IExtremaEnumerable ) instead of only one T item to:从这个issue 开始, min by 功能更改为返回 T 的IEnumerable (如果更准确地说: IExtremaEnumerable )而不是只有一个 T 项目:

public static IExtremaEnumerable<TSource> MinBy<TSource, TKey>(this IEnumerable<TSource> source,
        Func<TSource, TKey> selector, IComparer<TKey> comparer)

Usage Example:用法示例:

using MoreLinq;

IEnumerable<Test> testList = source.MinBy(p => p.Counter);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM