c# - Comment manipuler les nulls en LINQ en utilisant Min ou Max

Mots clés : c#.netlinqnullc#

meilleur 5 Réponses c# - Comment manipuler les nulls en LINQ en utilisant Min ou Max

vote vote

92

   var min = result.Partials.Where(o => o.IsPositive).Min(o => o.Result); 
 var min = result.Partials.Where(o => o.IsPositive)                           .Select(o => o.Result)                           .DefaultIfEmpty()                           .Min(); 
   var min = result.Partials.Where(o => o.IsPositive)                             .Min(o => (decimal?)o.Result); 
vote vote

81

result.Partials.Where(o => o.IsPositive).Select(o => o.Result).DefaultIfEmpty().Min(); 
vote vote

70

var query = result.Partials.Where(o => o.IsPositve); min = query.Any() ? query.Min(o => o.Result) : 0; // insert a different "default" value of your choice...     
vote vote

61

var min = result.Partials     .Where(o => o.IsPositive)     .Select(o => o.Result)     .Aggregate(0, Math.Min); // Or any other value which should be returned for empty list 
vote vote

53

public static class LinqExtensions {     public static TProp MinOrDefault<TItem, TProp>(this IEnumerable<TItem> This, Func<TItem, TProp> selector)     {         if (This.Count() > 0)         {             return This.Min(selector);         }         else         {             return default(TProp);         }     } } 
public class Model {     public int Result { get; set; } }  // ...  public void SomeMethod() {     Console.WriteLine("Hello World");     var filledList = new List<Model>     {         new Model { Result = 10 },         new Model { Result = 9 },     };     var emptyList = new List<Model>();     var minFromFilledList = filledList.MinOrDefault(o => o.Result)); // 9     var minFromEmptyList = emptyList.MinOrDefault(o => o.Result)); // 0 } 

Questions similaires