• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Find minimum values

 
Bartender
Posts: 669
15
TypeScript Fedora
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 80267
430
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 15737
368
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You will want to perform a GroupBy. This is what it looks like:
 
Al Hobbs
Bartender
Posts: 669
15
TypeScript Fedora
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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  
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
New web page for Paul's Rocket Mass Heaters movies
https://coderanch.com/t/785239/web-page-Paul-Rocket-Mass
reply
    Bookmark Topic Watch Topic
  • New Topic