为什么我在这里得到IndexOutOfRangeException?

use*_*670 0 c# linq algorithm

我无法弄清楚为什么我会在Where下面的条款中得到它.

using System;
using System.Linq;

public static class Extensions
{
    /// <summary>
    /// Removes consecutive characters,
    /// e.g. "aaabcc" --> "abc"
    /// </summary>
    public static void RemoveDuplicates(this string s)
    {
        var arr = s.ToCharArray()
                   .Where((i,c) => (i > 0) ? (c != s[i - 1]) : true)
                   .ToArray();
        s = new string(arr);

    }
}


public class Program
{   
    public static void Main()
    {
        var str = "aaabcc";
        str.RemoveDuplicates();
        Console.WriteLine(str);
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,还有一种方法可以在使用LINQ的同时使其更加高效和紧凑吗?

Dar*_*rov 5

这里的参数顺序错误:

.Where((i, c) => (i > 0) ? (c != s[i - 1]) : true)
Run Code Online (Sandbox Code Playgroud)

应成为:

.Where((c, i) => (i > 0) ? (c != s[i - 1]) : true)
Run Code Online (Sandbox Code Playgroud)