• 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
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Tim Holloway
  • Carey Brown
  • salvin francis

Find minimum values

 
Rancher
Posts: 480
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: 65466
249
  • 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: 10539
224
  • 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: 480
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  
 
a fool thinks himself to be wise, but a wise man knows himself to be a fool - shakespeare. foolish tiny ad:
Enterprise-grade Excel API for Java
https://products.aspose.com/cells/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!