C# Linq ElementAt 方法

csharpprogrammingserver side programming

C# 中的 ElementAt() 方法用于获取指定索引位置处的元素。

首先,设置字符串数组。

string[] str = { "Jack", "Pat", "David"};

现在,要获取特定索引处的元素,请使用 ElementAt() 方法,如以下示例所示 −

示例

using System.IO;
using System;
using System.Linq;
class Program {
   static void Main() {
      string[] str = { "Jack", "Pat", "David"};
      Random r = new Random(DateTime.Now.Second);
      // 生成随机字符串
      string res = str.AsQueryable().ElementAt(r.Next(0, str.Length));
      Console.WriteLine("Random Name = '{0}'", res);
   }
}

输出

Random Name = 'Jack'

相关文章