This is my sample data
var array = new string[] { "q", "we", "r", "ty", " ", "r" };
I want to take items from this collection until one of them don't meet the criteria, for example:
x => string.IsNullOrEmpty(x);
So after this:
var array = new string[] { "q", "we", "r", "ty", " ", "r" };
var newArray = array.TakeTo(x => string.IsNullOrEmpty(x));
newArray
should contains: "q", "we", "r", "ty"
I created this code:
public static class Extensions
{
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate)
{
if (items == null) throw new ArgumentNullException("items");
if (predicate == null) throw new ArgumentNullException("predicate");
var retVal = 0;
foreach (var item in items)
{
if (predicate(item)) return retVal;
retVal++;
}
return -1;
}
public static IEnumerable<TSource> TakeTo<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
var index = source.FindIndex(predicate);
if (index == -1)
return source;
return source.Take(index);
}
}
var array = new string[] { "q", "we", "r", "ty", " ", "r" };
var newArray = array.TakeTo(x => string.IsNullOrEmpty(x));
It works, but I am wondering if there is any built-in solution to that. Any ideas?