开发者

Getting first element of an IEnumerable item

开发者 https://www.devze.com 2023-03-01 06:12 出处:网络
I am returning an IEnumerable<object[]> element from a function that uses yield return in a loop.

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();


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()


Can't you use result.First()?


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


    public static T FirstOrDefault<T>(this IEnumerable items) where T : class {
        var list = items.OfType<T>();
        if (list!= null) {
            return list.FirstOrDefault();
        }

        return default(T);
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消