Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only the lowest values with Linq

Tags:

Hi I got the following linq for ordering my input after lowest value. But i would like it to only output the lowest values.

var sortedDict = (from entry in x where entry.Value > 0 orderby entry.Value ascending select entry); 

Now if it gets the following input.

3  4  2  6  2 

This would be my output

2  2  3  4  6 

What do I need to change in my linq so I only get this output

2  2 
like image 314
gulbaek Avatar asked Sep 29 '10 08:09

gulbaek


People also ask

How to get minimum value in LINQ c#?

In LINQ, you can find the minimum element of the given sequence by using Min() function. This method provides the minimum element of the given set of values. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#.

Which method can you use to find the minimum value in a sequence?

If your equation is in the form y = ax^2 + bx + c, you can find the minimum by using the equation min = c - b^2/4a. The first step is to determine whether your equation gives a maximum or minimum. This can be done by looking at the x^2 term.

Which method can you use to find the minimum value in a sequence C#?

The standard solution to get the minimum value in a sequence of values is using the Min() method.


2 Answers

Well, you could do:

int min = x.Min(entry => entry.Value); var lowestValues = x.Where(entry => entry.Value == min); 

Note that I've explicitly split these up, as if you use Where(entry => entry.Value == x.Min(y => y.Value)) it will look for the minimum on every iteration. On the other hand, that's true of LINQ to Objects - but in LINQ to SQL it would probably be better to do it all in one query, and let the database sort it out.

like image 106
Jon Skeet Avatar answered Oct 05 '22 01:10

Jon Skeet


You could try something like this:

data.Where (d => d == data.Min()) 

Note this is not necessarily the fastest way to do this.

like image 43
kjn Avatar answered Oct 05 '22 03:10

kjn