基于谓词拆分LINQ查询 [英] Splitting LINQ query based on predicate

查看:162
本文介绍了基于谓词拆分LINQ查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这将在谓词拆分的IEnumerable ,相对于谓词的索引分组物品放在一起的方法。例如,它可以拆分列表与LT;串> 在满足项目 X => MyRegex.Match(X).Success ,以之间这样的比赛被组合在一起的项目。

I'd like a method that would split an IEnumerable at a predicate, grouping items together by their index relative to the predicate. For example, it could split a List<string> at items satisfying x => MyRegex.Match(x).Success, with items "in between" such matches being grouped together.

其标志可能看起来行

public static IEnumerable<IEnumerable<TSource>> Split<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, bool> predicate,
    int bool count
)

,可能与包含所有分频器的输出的一个额外的元素

, possibly with an extra element of the output containing all of the dividers.

时有实现这个比的foreach 循环更高效和/或紧凑的方式?我觉得这应该是可能的LINQ的方法来实现,但我不能把我的手指上。

Is there a more efficient and/or compact way to implement this than a foreach loop? I feel like it should be possible to implement with LINQ methods, but I can't put my finger on it.

示例:

string[] arr = {"One", "Two", "Three", "Nine", "Four", "Seven", "Five"};
arr.Split(x => x.EndsWith("e"));



下列任一将是美好的:

Either of the following would be OK:

IEnumerable<string> {{}, {"Two"}, {}, {"Four", "Seven"}, {}}
IEnumerable<string> {{"Two"}, {"Four", "Seven"}}



为可选元素存储的比赛将是 {一,三,九,十一五}

推荐答案

您应该通过一个扩展方法做到这一点(这个方法可以让你忽略了分区项):

You should do this through an extension method (this method assumes you ignore the partitioned item):

/// <summary>Splits an enumeration based on a predicate.</summary>
/// <remarks>
/// This method drops partitioning elements.
/// </remarks>
public static IEnumerable<IEnumerable<TSource>> Split<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, bool> partitionBy,
    bool removeEmptyEntries = false,
    int count = -1)
{
    int yielded = 0;
    var items = new List<TSource>();
    foreach (var item in source)
    {
        if (!partitionBy(item))
            items.Add(item);
        else if (!removeEmptyEntries || items.Count > 0)
        {
            yield return items.ToArray();
            items.Clear();

            if (count > 0 && ++yielded == count) yield break;
        }
    }

    if (items.Count > 0) yield return items.ToArray();
}

这篇关于基于谓词拆分LINQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆