LINQ比较集合大小演变

1 .  LINQ比较集合大小演变

 


基本类:

public class Quote {
 public Stock Stock { get; set; }
 public decimal Price { get; set; }
 public DateTime Date { get; set; }
}

public class Stock {
 public string Name { get; set; }
 public List<Quote> Quotes { get; set; }
 public override string ToString() {
 return $"{Name}: MIN {Quotes.Min(q => q.Price)} - MAX {Quotes.Max(q => q.Price)}";
}


 

具体实现演变:

public partial class Program
{
private static void Sample01()
{
var stock = new Stock {Name = "Stock Demo"};
stock.Quotes = new List<Quote>
{
new Quote{Stock = stock, Price = 200, Date = DateTime.Parse("2020/3/29")},
new Quote{Stock = stock, Price = 150, Date = DateTime.Parse("2020/3/21")},
new Quote{Stock = stock, Price = 220, Date = DateTime.Parse("2020/3/23")},
new Quote{Stock = stock, Price = 180, Date = DateTime.Parse("2020/3/25")},
new Quote{Stock = stock, Price = 100, Date = DateTime.Parse("2020/3/26")},
};
Console.WriteLine( $"Stock: {stock}");

var tempMin = stock.Quotes.Aggregate((t, s) => t.Price < s.Price ? t : s);

var minQuote = stock.Quotes.MinItem(q => q.Date);


Console.WriteLine(minQuote.Price);
}

}


 

拓展实现:

public static class Sample01Extensions
{
  public static Quote MinPrice(this IEnumerable<Quote> source)
  {
    return source.Aggregate((t, s) => t.Price < s.Price ? t : s);
  }

   public static TSouce MinItem<TSouce, TCompareValue>(this IEnumerable<TSouce> source,
   Func<TSouce, TCompareValue> comparerExpression)
   {
     var comparer = Comparer<TCompareValue>.Default;
      return source.Aggregate((minValue, item) =>
      {

       var result = comparer.Compare(comparerExpression(minValue), comparerExpression(item));
       return result < 0 ? minValue : item;
      });
   }
}

总结: 用于拓展Linq 新的操作符!

posted @ 2022-01-05 14:13  根仔  阅读(49)  评论(0)    收藏  举报