tags:

views:

111

answers:

2

Hi,

I am using .NET 3.5. What method of the Array class is best for returning a empty index in an array (which can then be used for populating). The Single/SingleOrDefault() methods look good, but if there is more than one empty slot, I want the first with the lowest index.

EDIT: This is pretty easy with a loop, but I am looking at ways to do this in LINQ.

My current result in code is this:

              var x = from s in BaseArray
                    where s == null
                    select s;

But not tested and not sure how it will behave (will get more than one result in an empty array).

Thanks

+3  A: 
var result = list.Where(i => IsItemEmpty(i)).FirstOrDefault();

This simple linq statement will return the first "empty" item from the list. Of course, I've abstracted out how to decide if the item is empty as I don't know what your data structure looks like, but that should do it.

Joel Martinez
Perfect! Thanks for that, need to play with these methods more.
csharpdev
A: 

I've implemented this extension method. See if it's useful:

    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;
    }
bruno conde