替换重复序列

时间:2019-05-02 10:07:51

标签: c# linq

是否可以使用linq替换每个连续的重复项?我尝试使用小组没有成功。基本上,我需要得到以下结果:

string[] arr = new [] { "a", "a", "a", "b", "b", "b", "b", "c", "c", "c", "a", "a" }; // input
string[] res = new [] { "a", "R", "R", "b", "R", "R", "R", "c", "R", "R", "a", "R" }; // output

3 个答案:

答案 0 :(得分:8)

Select方法有一个重载,该重载会使用索引,您可以使用它来检查上一个项目:

res = arr.Select((x, idx) => idx != 0 && arr[idx - 1] == x ? "R" : x).ToArray();

答案 1 :(得分:-1)

您可以使用他所说的here的John Skeets Extension。

  public static IEnumerable<TResult> SelectWithPrevious<TSource, TResult>
    (this IEnumerable<TSource> source,
     Func<TSource, TSource, TResult> projection)
{
    using (var iterator = source.GetEnumerator())
    {
        if (!iterator.MoveNext())
        {
             yield break;
        }
        TSource previous = iterator.Current;
        while (iterator.MoveNext())
        {
            yield return projection(previous, iterator.Current);
            previous = iterator.Current;
        }
    }
}

然后像这样使用它:

var out  = arr.SelectWithPrevious((prev, curr) => prev==curr? R:curr));

答案 2 :(得分:-2)

这很好:

string[] arr = new [] { "a", "a", "a", "b", "b", "b", "b", "c", "c", "c", "a", "a" }; // input

string [] res = arr.StartWith("_").Zip(arr, (a0, a1) => a0 == a1 ? "R" : a1).ToArray();