Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first element of an IEnumerable item

Tags:

c#

generics

I am returning an IEnumerable<object[]> element from a function that uses yield return in a loop.

public static IEnumerable<object[]> GetData()
{
        ...

        connection.Open();

        using (OleDbDataReader dr = command.ExecuteReader())
        {
            while (dr.Read())
            {
            object[] array = new object[dr.FieldCount];
                dr.GetValues(array);
            yield return array;
            }
        }

        connection.Close();
}

What's the best way to retrieve the first element without using a loop preferably?

var result = Adapter.GetData();
like image 242
David Weng Avatar asked Apr 29 '11 05:04

David Weng


People also ask

What is first () in C#?

C# Linq First() Method Use the First() method to get the first element from an array. Firstly, set an array. int[] arr = {20, 40, 60, 80 , 100}; Now, use the Queryable First() method to return the first element.

How do I access IEnumerable?

The IEnumerable itself doesn't have Count , Start , or End . It's elements do, so you'll need to identify the element in the collection from which you want to read those values. For example, to read the values on the first element: var firstCount = list.

What does first do in Linq?

First<TSource>(IEnumerable<TSource>)Returns the first element of a sequence.

What is GetEnumerator C#?

The C# GetEnumerator() method is used to convert string object into char enumerator. It returns instance of CharEnumerator. So, you can iterate string through loop.


2 Answers

In short:

enumerator=result.GetEnumerator();
enumerator.MoveNext();
enumerator.Current;

This is what a foreach does in a loop to iterate through all the elements.

Proper way:

using (IEnumerator<object[]> enumerator = result.GetEnumerator()) {
    if (enumerator.MoveNext()) e = enumerator.Current;

}

With LINQ:

var e = result.First();

or

var e = result.FirstOrDefault(default);

Also:

var e = result.ElementAt(0);
like image 73
manojlds Avatar answered Oct 18 '22 20:10

manojlds


If your .Net 3.5 or higher

Adapter.GetData().First()
like image 1
Toby Avatar answered Oct 18 '22 19:10

Toby