如何特化现有的LINQ的操作符号

如何特化现有的LINQ的操作符号,以Where 为例子:

基本类:

复制代码

public interface IVisible
{
bool Visible { get; set; }
}

public class Customer : IVisible
{
 public string Name { get; set; }
 public int Age { get; set; }
 public bool Visible { get; set; }

 public Customer()
 {
  Visible = true;
 }

 public override string ToString()
 {
  return $"{Name} 今年 {Age} 岁了";
 }

}

复制代码

 

拓展实现:

复制代码

public static class Sample02Extensions
{
  public static IEnumerable<TSource> Where<TSource>(
  this IEnumerable<TSource> source,
 Func<TSource, bool> predicate) where TSource : IVisible
 {
  return Enumerable.Where(source, item => item.Visible == true && predicate(item));
  }
}

复制代码

调用列子:

复制代码

public partial class Program
{
 private static void Sample02()
 {
 var customers = new List<Customer>
 {
 new Customer{Name = "张三", Age = 20, Visible = false},
 new Customer{Name = "李四", Age = 18},
 new Customer{Name = "王五", Age = 22},
 };

 var query = from c in customers
                         where c.Age < 22 select c;

  foreach (var customer in query)
  {
  Console.WriteLine(customer);
  }
 }
}

复制代码

 

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