泛型方法

关于泛型方法,类Enumerable内含相当多的泛型方法的使用.Enumerable类定义的注释如下:

// 摘要:
//     提供一组用于查询实现 System.Collections.Generic.IEnumerable<T> 的对象的 static(在 Visual
//     Basic 中为 Shared)方法

由此注释,我们可以看到,凡是实现了System.Collections.Generic.IEnumerable<TSource>的对象都可以使用此类中定义的方法.

挑其中一个方法来看.

public static IEnumerable<TResult> Select<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, TResult> selector
)

返回值IEnumerable<TResult>:

返回值类型:

  • System.Collections.Generic.IEnumerable<TResult>

返回值:

  • 返回一个序列,此序列中的元素为对source中的每个元素调用selector方法后返回的元素结果.

类型参数<TSource, TResult>:

TSource:

  • source中元素的类型

TResult:

  • selector返回的值的类型

参数:

source:

  • System.Collections.Generic.IEnumerable<TSource>,一个值序列,要对该序列调用selector转换函数

selector:

  • System.Func<TSource, TResult>,应用于每个元素上的转换函数.

例子:

protected void Page_Load(object sender, EventArgs e)
{
    string[] strs = new string[]
    {
        "abcd",
        "abcee",
        "bcde",
        "123s"
    };

    //四种调用方法都可以
    //IEnumerable<string> result = strs.Select<string, string>(x => x.StartsWith("ab") ? x : string.Empty);
    //IEnumerable<string> result = strs.Select(x => x.StartsWith("ab") ? x : string.Empty);
    //IEnumerable<string> result = Enumerable.Select<string, string>(strs, x => x.StartsWith("ab") ? x : string.Empty);
    IEnumerable<string> result = Enumerable.Select(strs, x => x.StartsWith("ab") ? x : string.Empty);
    foreach (var r in result)
    {
        Response.Write(r.ToString()+"<br/>");
    }
}

效果:

abcd
abcee

转载于:https://www.cnblogs.com/loveYN/p/4509716.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值