本文共 2263 字,大约阅读时间需要 7 分钟。
ElementAt()和ElementAtOrDefault()是C#集合中常用的方法,用于数组和集合的索引访问操作。ElementAt()方法可以用来快速获取指定索引位置的元素,这与直接使用数组索引器[]的效果相似。ElementAt()适用于所有实现IEnumerable
ElementAt()方法的定义如下:
public static TSource ElementAt(this IEnumerable source, int index);
该方法接收一个IEnumerable
ElementAtOrDefault()方法类似于ElementAt(),但其主要区别在于当指定索引超出有效范围或为负数时,它不会抛出异常,而是返回该类型的默认值(null或零值,具体取决于TSource类型)。其定义如下:
public static TSource ElementAtOrDefault(this IEnumerable source, int index);
以下是ElementAt()和ElementAtOrDefault()的示例代码:
public static class Program{ private static readonly int SELECTED_INDEX = 4; public static void Main(string[] args) { int[] numbers = new int[] {1, 2, 3, 5, 7, 11}; int result = numbers.ElementAt(SELECTED_INDEX); Console.WriteLine("数据:{0}", numbers.Text()); Console.WriteLine("指定索引:{0}", SELECTED_INDEX); Console.WriteLine("结果:{0}", result); Console.ReadKey(); } public static string Text(this IEnumerable i_source) { string text = string.Empty; foreach (var value in i_source) { text += string.Format("[{0}], ", value); } return text; }}// ElementAtOrDefault()示例public static class Program{ private static readonly int SELECTED_INDEX = -1; public static void Main(string[] args) { int[] numbers = new int[] {1, 2, 3, 5, 7, 11}; int result = 0; try { result = numbers.ElementAtOrDefault(SELECTED_INDEX); } catch (System.Exception i_exception) { Console.WriteLine("异常:{0}", i_exception); Console.ReadKey(); return; } Console.WriteLine("数据:{0}", numbers.Text()); Console.WriteLine("指定索引:{0}", SELECTED_INDEX); Console.WriteLine("结果:{0}", result); Console.ReadKey(); }} 转载地址:http://bfnq.baihongyu.com/