gpt4 book ai didi

c# - Linq:返回具有给定类型的第一个实例的方法

转载 作者:太空狗 更新时间:2023-10-30 00:10:32 25 4
gpt4 key购买 nike

我经常发现自己写的代码是这样的:

collection.First(s => s is MyType) as MyType;

是否有更具体的 Linq 方法,返回特定类型的第一个元素?

像这样:

collection.FirstOfType<MyType>();

我也看过 Jon Skeets MoreLinq项目,但运气不好

最佳答案

使用 Enumerable.OfType<T> 按指定类型过滤集合:

collection.OfType<MyType>().First();

注意 - 如果可能没有 MyType 的项目存在于集合中,然后使用 FirstOrDefault()以避免异常。

内部OfType只需使用 is运算符产生与给定类型兼容的所有项目。像这样的东西(实际上 OfType 返回 OfTypeIterator 迭代集合):

public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source)
{
foreach (object obj in source)
{
if (!(obj is TResult))
continue;

yield return (TResult)obj;
}
}

关于c# - Linq:返回具有给定类型的第一个实例的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22387615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com