将指向数组中特定元素的引用

21 浏览
0 Comments

将指向数组中特定元素的引用

这是我的示例数据

var array = new string[]  { "q", "we", "r", "ty", " ", "r" };

我想从这个集合中获取项目,直到其中一个不符合条件为止,例如:

x => string.IsNullOrEmpty(x);

所以在这之后:

var array = new string[]  { "q", "we", "r", "ty", " ", "r" };
var newArray = array.TakeTo(x => string.IsNullOrEmpty(x));

newArray 应该包含:\"q\", \"we\", \"r\", \"ty\"

我创建了这段代码:

public static class Extensions
{
    public static int FindIndex(this IEnumerable 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 TakeTo(this IEnumerable 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));

它可以工作,但我想知道是否有任何内置的解决方案。有任何想法吗?

admin 更改状态以发布 2023年5月22日
0
0 Comments

juharr在评论中提到,你应该使用TakeWhile,很可能这正是你要找的。

对于你的情况,你要寻找的代码是:

var array = new string[]  { "q", "we", "r", "ty", " ", "r" };
var newArray = array.TakeWhile(x => !string.IsNullOrWhiteSpace(x)).ToArray();

值得注意的是,我用IsNullOrWhiteSpace替换了IsNullOrEmpty调用,这很重要,因为IsNullOrEmpty如果有任何空格存在,将返回false

TakeWhile的作用基本上就是遍历枚举元素并让它们符合你给定的函数,不断添加到返回的集合中,直到该函数不再返回true为止,此时它停止遍历元素并返回到目前为止收集到的内容。换句话说,它是在符合你给定条件的情况下“取…”的。

在你的示例中,TakeWhile将在你的array变量的第4个索引处停止集合,因为它只包含空格,并返回“q”,“we”,“r”,“ty”

0