c# - 在 C# 中使用 LINQ 进行分组 - 索引越界

标签 c# linq indexoutofboundsexception

我试图根据字符串的扩展名(最后三个字符)对字符串进行分组,以训练我的 LINQ 技能(我是新手),但我不断遇到异常:

System.ArgumentOutOfRangeException: 'Index and length must refer to a location within the string.

我的代码如下:我的错误在哪里?

string[] files = new string[10] {"OKO.pdf","aaa.frx", "bbb.TXT", "xyz.dbf","abc.pdf", "aaaa.PDF","xyz.frt", "abc.xml", "ccc.txt", "zzz.txt"};

var res = from file in files
    group file by file.Substring(file.IndexOf(".")+1,file.Length-1) into extensions
    select extensions;

var res1 = files.GroupBy(file => file.Substring(file.IndexOf("."), file.Length - 1));

foreach(var group in res)
{
    Console.WriteLine("There are {0} files with the {1} extension.", group.Count(), group.Key);
}

最佳答案

正如jdweng在评论部分提到的。您只需要使用 Substring 的重载

The substring starts at a specified character position and continues to the end of the string.

string[] files = new string[10] { "OKO.pdf", "aaa.frx", "bbb.TXT", "xyz.dbf", "abc.pdf", "aaaa.PDF", "xyz.frt", "abc.xml", "ccc.txt", "zzz.txt" };

var res = from file in files
          group file by file.Substring(file.IndexOf(".") + 1) into extensions
          select extensions;

foreach (var group in res)
{
    Console.WriteLine("There are {0} files with the {1} extension.", group.Count(), group.Key);
}

结果将是:

There are 2 files with the pdf extension.
There are 1 files with the frx extension.
There are 1 files with the TXT extension.
There are 1 files with the dbf extension.
There are 1 files with the PDF extension.
There are 1 files with the frt extension.
There are 1 files with the xml extension.
There are 2 files with the txt extension

关于c# - 在 C# 中使用 LINQ 进行分组 - 索引越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59739303/

相关文章:

java - 如何正确填充 ArrayList<String> 类型的 ArrayList?

selenium - 无法使用 Java/Selenium 脚本读取 Excel 工作表中存在的所有数据

c# - 在 ASP.NET Core Identity UI 中更改路由?

c# - 具有 Build Action=Content 的文件是否在执行时加载到内存中?

c# - 使用 F5 时,终于似乎没有在 C# 控制台应用程序中执行

c# - 从 ICollection<T> 到 List<T> 的 Linq 转换

linq - LINQ扩展在CSharpCodeProvider内部不可用

c# - CA2100 : Review SQL queries for security vulnerabilities

c# - .Any() 上的 Linq 和 EF

java - Hangman 游戏中的 ArrayIndexOutOfBoundsException