tags:

views:

89

answers:

3

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
+4  A: 

You could try something like this:

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

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

KJN
Thanks for your help KJN
gulbaek
+1  A: 

First, find the lowest value:

var min = (from entry in x where entry.Value > 0 select entry).Min();

Then, select items:

var sortedDict = from entry in x where entry.Value == min select entry

Sorting is not needed for your scenario.

Michael Damatov
Thanks for being the only one to rember checking for numbers above 0 :-)
gulbaek
+6  A: 

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.

Jon Skeet
Will this be faster than KJN's answer? Will his answer cause Min() to be recalculated for each entry inside the data list, or will the compiler do some caching of this value. I doubt it, but I would like to get it confirmed one way or the other.
Øyvind Bråthen
Yes it will typically be faster. :)
KJN
@Øyvind Bråthen: If you're using LINQ to Objects, then yes - Min() will be recalculated for each entry in the list.
Jon Skeet
Thanks alot Jon Skeet :-)
gulbaek