简体   繁体   English

C#IEnumerable检索第一条记录

[英]C# IEnumerable Retrieve The First Record

I have an IEnumerable list of objects in C#. 我在C#中有一个IEnumerable对象列表。 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? 我可以为每个对象使用a来循环检查每个对象,但是在这种情况下,我要做的就是检查第一个对象是否有一种无需使用foreach循环即可执行此操作的方法?

I've tried mylist[0] but that didnt work. 我已经尝试过mylist [0],但是没有用。

Thanks 谢谢

(For the sake of convenience, this answer assumes myList implements IEnumerable<string> ; replace string with the appropriate type where necessary.) (为方便起见,此答案假定myList实现IEnumerable<string> ;必要时将string替换为适当的类型。)

If you're using .NET 3.5, use the First() extension method: 如果使用的是.NET 3.5,请使用First()扩展方法:

string first = myList.First();

If you're not sure whether there are any values or not, you can use the FirstOrDefault() method which will return null (or more generally, the default value of the element type) for an empty sequence. 如果不确定是否有任何值,则可以使用FirstOrDefault()方法,该方法将为空序列返回null (或更FirstOrDefault()是,元素类型的默认值)。

You can still do it "the long way" without a foreach loop: 您仍然可以在没有foreach循环的情况下“长期进行”:

using (IEnumerator<string> iterator = myList.GetEnumerator())
{
    if (!iterator.MoveNext())
    {
        throw new WhateverException("Empty list!");
    }
    string first = iterator.Current;
}

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. 您需要调用MoveNext()将其移动到第一个元素,这就是如何区分空序列和其中包含单个元素的序列的区别。

EDIT: Just thinking about it, I wonder whether this is a useful extension method: 编辑:只是考虑一下,我想知道这是否是一个有用的扩展方法:

public static bool TryFirst(this IEnumerable<T> source, out T value)
{
    using (IEnumerator<T> iterator = source.GetEnumerator())
    {
        if (!iterator.MoveNext())
        {
            value = default(T);
            return false;
        }
        value = iterator.Current;
        return true;
    }
}

Remember, there may be no "first element" if the sequence is empty. 请记住,如果序列为空,则可能没有“第一个元素”。

        IEnumerable<int> z = new List<int>();
        int y = z.FirstOrDefault();

If you're not on 3.5: 如果您未使用3.5:

 using (IEnumerator<Type> ie = ((IEnumerable<Type>)myList).GetEnumerator()) {
     if (ie.MoveNext())
         value = ie.Current;
     else
         // doesn't exist...
 }

or 要么

 Type value = null;
 foreach(Type t in myList) {
     value = t;
     break;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM