C# 从数组中获取索引最低的空插槽

C# 从数组中获取索引最低的空插槽,c#,.net,linq,arrays,C#,.net,Linq,Arrays,我正在使用.NET3.5。数组类的哪个方法最适合返回数组中的空索引(然后可以用于填充)。Single/SingleOrDefault()方法看起来不错,但是如果有多个空槽,我希望第一个槽的索引最低 编辑:使用循环非常简单,但我正在寻找在LINQ中实现这一点的方法 我目前的代码结果如下: var x = from s in BaseArray where s == null select s

我正在使用.NET3.5。数组类的哪个方法最适合返回数组中的空索引(然后可以用于填充)。
Single/SingleOrDefault()
方法看起来不错,但是如果有多个空槽,我希望第一个槽的索引最低

编辑:使用循环非常简单,但我正在寻找在LINQ中实现这一点的方法

我目前的代码结果如下:

              var x = from s in BaseArray
                    where s == null
                    select s;
但未测试,也不确定其行为(将在空数组中获得多个结果)

谢谢


这个简单的linq语句将返回列表中的第一个“空”项。当然,我已经抽象出了如何判断该项是否为空,因为我不知道您的数据结构是什么样子的,但应该这样做。

我已经实现了这个扩展方法。看看它是否有用:

    public static int? FirstEmptyIndex<T>(this IEnumerable<T> src)
    {
        using (IEnumerator<T> e = src.GetEnumerator())
        {
            int index = 0;
            while (e.MoveNext())
            {
                if (e.Current == null)
                    return index;
                else
                    index++;
            }
        }
        return null;
    }
公共静态int?FirstEmptyIndex(此IEnumerable src)
{
使用(IEnumerator e=src.GetEnumerator())
{
int指数=0;
while(如MoveNext())
{
如果(e.Current==null)
收益指数;
其他的
索引++;
}
}
返回null;
}

完美!谢谢,我们需要更多地使用这些方法。
    public static int? FirstEmptyIndex<T>(this IEnumerable<T> src)
    {
        using (IEnumerator<T> e = src.GetEnumerator())
        {
            int index = 0;
            while (e.MoveNext())
            {
                if (e.Current == null)
                    return index;
                else
                    index++;
            }
        }
        return null;
    }