Win a copy of Modern JavaScript for the Impatient this week in the Server-Side JavaScript and NodeJS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Find minimum values

 
Rancher
Posts: 527
6
IntelliJ IDE Spring Fedora
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I am trying to get the cleanest way to get the objects with the smallest values.

I know how to get just one :

list.OrderBy(d => d.size).FirstOrDefault();



But if there are multiple objects with the minimum size I want all of them.  
Right now I am planning on doing:

var min =  list.Min(d => size);
return list.Where(d => d.size =  min);



Is there another linq method that maybe I'm looking over?

If there is no better way in C# is there maybe a cleaner solution in Java streams?

Thanks!  
 
Marshal
Posts: 70211
280
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't know about Linq/C#, but this is the nearest I could think of in Java┬«:-Maybe you could do it with one pass, but I think you would need an object to count the minimum value; remember local variables used in a λ must be effectively final.
 
Saloon Keeper
Posts: 12251
259
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will want to perform a GroupBy. This is what it looks like:
 
Al Hobbs
Rancher
Posts: 527
6
IntelliJ IDE Spring Fedora
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:You will want to perform a GroupBy.



Oh returning empty enumerable looks way better.  Nice!!!
I didn't understand it at first but it groups the objects by their value then takes the first one.  Very clean!!!
Thanks  
 
Don't get me started about those stupid light bulbs.
    Bookmark Topic Watch Topic
  • New Topic