繁体   English   中英

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

[英]Grouping with LINQ in C# - Index out of bounds

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

System.ArgumentOutOfRangeException: '索引和长度必须指向字符串中的一个位置。

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

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 的重载

子字符串从指定的字符位置开始,一直到字符串的末尾。

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

由于您的文件名可以包含点,如果您使用IndexOf ,点的位置可能不正确。 您可以使用Split方法来解决这个问题(注意有一个带点OKO.ZOKO.pdf的文件并查看输出):

static void other()
{
    var names = new[] { "OKO.pdf", "OKO.ZOKO.pdf", "aaa.frx", "bbb.TXT", "xyz.dbf", "abc.pdf" };
    var x = names.GroupBy(n => n.Split('.').Last());
    x.ToList().ForEach(g => WriteLine($"There are {g.Count()} files with extension '{g.Key}'"));
}

// Output:
//    There are 3 files with extension 'pdf'
//    There are 1 files with extension 'frx'
//    There are 1 files with extension 'TXT'
//    There are 1 files with extension 'dbf'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM