111,121
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Compsognathus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Oviraptor");
dinosaurs.Add("Velociraptor");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Dilophosaurus");
dinosaurs.Add("Gallimimus");
dinosaurs.Add("Triceratops");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nFindIndex(EndsWithSaurus): {0}",
dinosaurs.FindIndex(EndsWithSaurus));
Console.WriteLine("\nFindIndex(2, EndsWithSaurus): {0}",
dinosaurs.FindIndex(2, EndsWithSaurus));
Console.WriteLine("\nFindIndex(2, 3, EndsWithSaurus): {0}",
dinosaurs.FindIndex(2, 3, EndsWithSaurus));
}
// Search predicate returns true if a string ends in "saurus".
private static bool EndsWithSaurus(String s)
{
if ((s.Length > 5) &&
(s.Substring(s.Length - 6).ToLower() == "saurus"))
{
return true;
}
else
{
return false;
}
}
}
/* This code example produces the following output:
Compsognathus
Amargasaurus
Oviraptor
Velociraptor
Deinonychus
Dilophosaurus
Gallimimus
Triceratops
FindIndex(EndsWithSaurus): 1
FindIndex(2, EndsWithSaurus): 5
FindIndex(2, 3, EndsWithSaurus): -1
*/
public int FindIndex(int startIndex, Predicate<T> match)
{
return this.FindIndex(startIndex, this._size - startIndex, match);
}
public int FindIndex(int startIndex, int count, Predicate<T> match)
{
if (startIndex > this._size)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
if ((count < 0) || (startIndex > (this._size - count)))
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
}
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
int num = startIndex + count;
for (int i = startIndex; i < num; i++)
{
if (match(this._items[i]))
{
return i;
}
}
return -1;
}