I have an IEnumerable list of objects in C#. I can use a for each to loop through and examine each object fine, however in this case all I want to do is examine the first object is there a way to do this without using a foreach loop?
I’ve tried mylist[0] but that didnt work.
Thanks
(For the sake of convenience, this answer assumes
myListimplementsIEnumerable<string>; replacestringwith the appropriate type where necessary.)If you’re using .NET 3.5, use the
First()extension method:If you’re not sure whether there are any values or not, you can use the
FirstOrDefault()method which will returnnull(or more generally, the default value of the element type) for an empty sequence.You can still do it “the long way” without a
foreachloop:It’s pretty ugly though 🙂
In answer to your comment, no, the returned iterator is not positioned at the first element initially; it’s positioned before the first element. You need to call
MoveNext()to move it to the first element, and that’s how you can tell the difference between an empty sequence and one with a single element in.EDIT: Just thinking about it, I wonder whether this is a useful extension method: