使用LINQ在列表中查找特定类型的第一个元素 [英] Find first element of certain type in a list using LINQ

查看:98
本文介绍了使用LINQ在列表中查找特定类型的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用LINQ和C#在元素列表中查找具有某种类型的第一项的最短表示法是什么.

What would be the shortest notation to find the first item that is of a certain type in a list of elements using LINQ and C#.

推荐答案

var first = yourCollection.OfType<YourType>().First();

请注意, First 如果没有类型为YourType的元素,则该方法将引发异常.如果您不希望这样做,则可以使用 Take(1) ,具体取决于行为你确实想要.

Note that the First method will throw an exception if there are no elements of type YourType. If you don't want that then you could use FirstOrDefault or Take(1) instead, depending on the behaviour you do want.

这篇关于使用LINQ在列表中查找特定类型的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆