gpt4 book ai didi

c# - 为什么我会在这里收到 IndexOutOfRangeException?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:29:13 25 4
gpt4 key购买 nike

我不明白为什么我在下面的 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);
}
}

另外,有没有办法在仍然使用 LINQ 的情况下使它稍微更高效、更紧凑?

最佳答案

这里的参数顺序错误:

.Where((i, c) => (i > 0) ? (c != s[i - 1]) : true)

应该变成:

.Where((c, i) => (i > 0) ? (c != s[i - 1]) : true)

关于c# - 为什么我会在这里收到 IndexOutOfRangeException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38628682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com