How to access the first element in an object which implemented IEnumerable
Only want to access the first element in an object which implemented IEnumerable, how t开发者_Python百科o do that?
Unfortunately you can’t use the LINQ extension methods on something which implements only IEnumerable
. You can, however, use .Cast<object>()
to turn it into an IEnumerable<object>
and then use the following methods. The following assumes that collection
is of type IEnumerable<T>
for some T
:
To access the first element and throw an exception if there is none:
collection.First()
To access the first element and get the type’s default value if there is none:
collection.FirstOrDefault()
The type’s default value is null
for reference types (types declared as class
, for example string
, Stream
, Bitmap
, etc.) and the “zero value” for value types (types declared as struct
or enum
, for example int
, bool
, DateTime
, etc.).
To only find out whether there is a first element at all:
collection.Any()
All three of these can take a lambda expression as a condition, e.g. .First(x => x.Name == "x")
, which is equivalent to .Where(x => x.Name == "x").First()
.
use the FirstOrDefault method
using System.Linq;
int[] numbers = { };
int first = numbers.FirstOrDefault();
精彩评论