Guest User

LINQ Min Example

a guest
Oct 11th, 2012
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.33 KB | None | 0 0
  1. void Main()
  2. {
  3.     var bronze = new ElementType { Name = "Bronze" };
  4.     var steel = new ElementType { Name = "Steel" };
  5.    
  6.     var weakBronzeBeam = new Beam { Ix = 50, ElementType = bronze };
  7.     var strongBronzeBeam = new Beam { Ix = 100, ElementType = bronze };
  8.    
  9.     var weakSteelBeam = new Beam { Ix = 80, ElementType = steel };
  10.     var strongSteelBeam = new Beam { Ix = 200, ElementType = steel };
  11.    
  12.     var data = new [] { weakBronzeBeam, strongBronzeBeam, weakSteelBeam, strongSteelBeam };
  13.    
  14.     var iRequired = 70;
  15.    
  16.     var smallestBeamForTypes =
  17.         from anyBeam in data
  18.         where anyBeam.Ix >= iRequired
  19.         group anyBeam by anyBeam.ElementType into beamTypeGroups
  20.         let minIx = beamTypeGroups.Min(beam => beam.Ix)
  21.         select new {
  22.             ElementType = beamTypeGroups.Key,
  23.             SmallestBeam = beamTypeGroups.First(beam => beam.Ix == minIx)
  24.         };
  25.        
  26.     foreach(var smallestBeamForType in smallestBeamForTypes)
  27.     {
  28.         String.Format("For the element type {0} the smallest beam is {1}",
  29.             smallestBeamForType.ElementType , smallestBeamForType.SmallestBeam).Dump();
  30.     }  
  31. }
  32.  
  33. class ElementType
  34. {
  35.     public string Name { get; set; }
  36.    
  37.     public override string ToString()
  38.     {
  39.         return Name;
  40.     }
  41. }
  42.  
  43. class Beam
  44. {
  45.     public int Ix { get; set; }
  46.     public ElementType ElementType { get; set; }
  47.    
  48.     public override string ToString()
  49.     {
  50.         return Ix.ToString();
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment