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();
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.
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.
First<TSource>(IEnumerable<TSource>)Returns the first element of a sequence.
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.
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);
If your .Net 3.5 or higher
Adapter.GetData().First()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With