Linq-1.自己手写一个扩展方法

本文展示了如何使用C#编写自定义扩展方法来实现与Linq的Where方法类似的功能。通过对比调用Linq的Where方法和自定义的扩展方法,解释了两种方法在处理数据过滤时的实现原理。文中提供了两种自定义扩展方法的实现方式,一种是将结果存储到列表中,另一种则是使用yield return逐个返回结果。
摘要由CSDN通过智能技术生成

1.调用Linq的Where扩展方法

/// <summary>
/// Where方法会遍历集合中的每个元素
/// 每个元素调用 x => x > 10 表达式判断是否为true
/// 如果为true,则把这个值放到返回的集合中
/// </summary>
{
    int[] nums1 = new int[] { 11, 2, 3, 5, 6, 7, 8, 14, 18, 22 };
    IEnumerable<int> result1 = nums1.Where(x => x > 10);
    foreach (var item in result1)
    {
        Console.WriteLine($"result1:{item}");
    }
}

2.自己写一个扩展方法代替Where

/// <summary>
/// 自己写扩展方法 一:
/// </summary>
{
    int[] nums2 = new int[] { 11, 2, 3, 5, 6, 7, 8, 14, 18, 22 };
    IEnumerable<int> result2 = MyWhere1(nums2, a => a > 10);
    foreach (var item in result2)
    {
        Console.WriteLine($"result2:{item}");
    }


    static IEnumerable<int> MyWhere1(IEnumerable<int> items, Func<int, bool> F)
    {
        List<int> list = new List<int>();
        foreach (int item in items)
        {
            if (F(item))
            {
                list.Add(item);
            }
        }
        return list;
    }
}

3.自己又写一个扩展方法代替Where

/// <summary>
/// 自己写扩展方法 二:
/// </summary>
{
    int[] nums3 = new int[] { 11, 2, 3, 5, 6, 7, 8, 14, 18, 22 };
    IEnumerable<int> result3 = MyWhere2(nums3, a => a > 10);
    foreach (var item in result3)
    {
        Console.WriteLine($"result2:{item}");
    }


    static IEnumerable<int> MyWhere2(IEnumerable<int> items, Func<int, bool> F)
    {
        foreach (int item in items)
        {
            if (F(item))
            {
                yield return item;
            }
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DotNeter-Hpf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值