T>我如何从一个IEnumerable&LT拿到的第一个元素;在.net中?
我常常想抓住的的IEnumerable和其中的第一个元素; T>
在.NET中,我还没有找到一个很好的办法做到这一点。我拿出最好的是:
I often want to grab the first element of an IEnumerable<T>
in .net, and I haven't found a nice way to do it. The best I've come up with is:
foreach(Elem e in enumerable) {
// do something with e
break;
}
呸!那么,有没有一个很好的办法做到这一点?
Yuck! So, is there a nice way to do this?
如果你能使用LINQ,你可以使用:
If you can use LINQ you can use:
var e = enumerable.First();
这将抛出一个异常,但如果枚举为空:在这种情况下,你可以使用:
This will throw an exception though if enumerable is empty: in which case you can use:
var e = enumerable.FirstOrDefault();
FirstOrDefault()
返回默认(T)
如果枚举是空的,这将是空
引用类型或默认的零值值类型。
FirstOrDefault()
will return default(T)
if the enumerable is empty, which will be null
for reference types or the default 'zero-value' for value types.
如果您不能使用LINQ,那么你的做法是技术上是正确的,也比使用创造一个枚举的的GetEnumerator
和的MoveNext 没有什么不同code>方法来检索的第一个结果(此例中假定枚举是一个
的IEnumerable&LT; ELEM&GT;
):
If you can't use LINQ, then your approach is technically correct and no different than creating an enumerator using the GetEnumerator
and MoveNext
methods to retrieve the first result (this example assumes enumerable is an IEnumerable<Elem>
):
Elem e = myDefault;
using (IEnumerator<Elem> enumer = enumerable.GetEnumerator()) {
if (enumer.MoveNext()) e = enumer.Current;
}
乔尔Coehoorn 的提到。单()
的的意见;这也将工作,如果你期待您的枚举包含一个元素 - 但如果它是空的或多个元素大会抛出异常。有一个相应的的SingleOrDefault()
方法覆盖此方案以类似的方式来 FirstOrDefault()
。然而,大卫乙解释说,的SingleOrDefault()
仍觉在将可枚举包含多个项目的情况下抛出异常。
Joel Coehoorn mentioned .Single()
in the comments; this will also work, if you are expecting your enumerable to contain exactly one element - however it will throw an exception if it is either empty or larger than one element. There is a corresponding SingleOrDefault()
method that covers this scenario in a similar fashion to FirstOrDefault()
. However, David B explains that SingleOrDefault()
may still throw an exception in the case where the enumerable contains more than one item.
编辑:感谢马克Gravell 获取指出,我需要处理我的 IEnumerator的
对象,用了之后 - 我已经编辑了非LINQ的例子,显示了使用
关键字来实现这个模式
Thanks Marc Gravell for pointing out that I need to dispose of my IEnumerator
object after using it - I've edited the non-LINQ example to display the using
keyword to implement this pattern.