借助Array类操作数组

c sharp中对定义好的数组,提供了一个Array类,方便的操作该数组。使用示例如下:

using System;

public sealed class Program
{
    public static void Main()
    {
        string[] names = {"Owen", "Ricy", "Vincent", "Lynn"};

        // find name with letter 'n', return the first satisfied element
        Console.WriteLine(Array.Find(names, name => name.IndexOf('n') >= 0));

        // find names with letter 'n'
        foreach(string name in Array.FindAll(names, name => name.IndexOf('n') >= 0))
            Console.WriteLine(name);

        // whether a certain element contained in the array
        if(Array.Exists(names, name => name.Length > 4))
            Console.WriteLine("Name with more than 4 letters exist");

        // print every name
        Array.ForEach(names, Console.WriteLine);
    }
}

需注意,Find方法需要传入两个参数,第一个为被操作的数组,第二个为一个返回值为bool方法A,该方法接受一个数组元素类型的参数。此处使用lambda表达式简化了方法的定义。Find方法返回第一个传入方法A得到返回值为true的元素。FindAll方法则返回所有满足条件的元素。
运行结果如下:
运行结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值