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 @   根仔  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示