Get empty slot with lowest index from an array
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 no开发者_开发技巧t tested and not sure how it will behave (will get more than one result in an empty array).
Thanks
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.
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;
}
精彩评论