List
列表的属性:
- 它与数组不同。列表可以动态调整大小,但数组则不能。
- 列表类可以接受null作为引用类型的有效值,并且还允许重复的元素。
- 如果计数通过重新分配内部数组自动变成等于容量则的列表的容量增加。在添加新元素之前,现有元素将被复制到新数组。
句法:
public T Find (Predicate match);
范围:
match: It is the Predicate delegate which defines the conditions of the element which is to be searched.
返回值:如果找到该元素,则此方法将返回与指定谓词定义的条件匹配的第一个元素,否则将返回类型T的默认值。
异常:如果匹配为null,则此方法将提供ArgumentNullException。
下面的程序说明了List
范例1:
// C# Program to get the first occurrence
// of the element that match the specified
// conditions defined by the predicate
using System;
using System.Collections;
using System.Collections.Generic;
class Geeks {
// function which checks whether an
// element is even or not. Or you can
// say it is the specified condition
private static bool isEven(int i)
{
return ((i % 2) == 0);
}
// Main Method
public static void Main(String[] args)
{
// Creating an List of Integers
List firstlist = new List();
// Adding elements to List
firstlist.Add(2);
firstlist.Add(4);
firstlist.Add(7);
firstlist.Add(2);
firstlist.Add(6);
firstlist.Add(2);
firstlist.Add(2);
Console.WriteLine("Elements Present in List:\n");
// Displaying the elements of List
foreach(int k in firstlist)
{
Console.WriteLine(k);
}
Console.WriteLine(" ");
Console.Write("Result: ");
// Will give the first occurrence of the
// element of firstlist that match the
// conditions defined by predicate
Console.WriteLine(firstlist.Find(isEven));
}
}
输出:
Elements Present in List:
2
4
7
2
6
2
2
Result: 2
范例2:
// C# Program to get the first occurrence
// of the element that match the specified
// conditions defined by the predicate
using System;
using System.Collections;
using System.Collections.Generic;
class Geeks {
// function which checks whether an
// element is even or not. Or you can
// say it is the specified condition
private static bool isEven(int i)
{
return ((i % 2) == 0);
}
// Main Method
public static void Main(String[] args)
{
// Creating an List of Integers
List firstlist = new List();
// Adding elements to List
firstlist.Add(5);
firstlist.Add(7);
firstlist.Add(9);
firstlist.Add(11);
firstlist.Add(3);
firstlist.Add(17);
firstlist.Add(19);
Console.WriteLine("Elements Present in List:\n");
// Displaying the elements of List
foreach(int k in firstlist)
{
Console.WriteLine(k);
}
Console.WriteLine(" ");
Console.Write("Result: ");
// Will give the first occurrence of the
// element of firstlist that match the
// conditions defined by predicate
// No match found so it will return 0
Console.WriteLine(firstlist.Find(isEven));
}
}
输出:
Elements Present in List:
5
7
9
11
3
17
19
Result: 0
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.list-1.find?view=netframework-4.7.2