在C#中,First()
和Find()
是两种不同的方法,分别属于LINQ和List<T>
类,它们的用途、行为和应用场景有显著区别。以下是详细对比:
First()
System.Linq
IEnumerable<T>
的集合(如数组、List、LINQ查询结果等)。InvalidOperationException
。Find()
List<T>
(非LINQ方法,是List<T>
的成员方法)。Predicate<T>
委托搜索列表中第一个匹配的元素。List<T>
或其子类。null
或0
)。| 特性 | First()
| Find()
|
|---------------------|-----------------------------------|-----------------------------------|
| 来源 | LINQ扩展方法 | List<T>
的实例方法 |
| 输入参数 | Lambda表达式或无条件 | Predicate<T>
委托 |
| 返回值 | 匹配的第一个元素 | 匹配的第一个元素或默认值 |
| 空集合/无匹配 | 抛出异常 | 返回default(T)
(如null
) |
| 性能 | 需要遍历序列(可能全扫描) | 直接遍历列表(优化过的内部实现) |
First()
using System.Linq;
List<int> numbers = new List<int> { 1, 2, 3, 4 };
// 返回第一个偶数
int firstEven = numbers.First(x => x % 2 == 0); // 输出: 2
// 空集合时抛出异常
List<int> emptyList = new List<int>();
// int item = emptyList.First(); // 抛出 InvalidOperationException
Find()
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
// 查找第一个长度大于3的名字
string result = names.Find(name => name.Length > 3); // 输出: "Alice"
// 无匹配时返回 null
string notFound = names.Find(name => name.Length > 10); // 输出: null
First()
FirstOrDefault()
避免异常)。Find()
List<T>
且希望无匹配时静默返回默认值。Find()
通常比LINQ的First()
略快,因省去LINQ抽象层)。First()
抛出异常而Find()
不抛?First()
强调“必须有元素”,而Find()
是列表的实用方法,倾向于容错。FirstOrDefault()
替代First()
。First()
:代码需要通用性(支持所有IEnumerable<T>
)。Find()
:仅操作List<T>
且需避免异常。List<T>
,Find()
略快于First()
(因直接访问内部数组)。First()
。通过理解这些差异,可以更精准地选择适合场景的方法。
没有搜到相关的文章