c# - 在 C# 中使用 LINQ 分组 - 索引超出范围
问题描述
我正在尝试根据字符串的扩展名(最后三个字符)对字符串进行分组,以训练我的 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
推荐阅读
- python - 为什么我收到以下错误消息:+ 的不支持的操作数类型:'int' 和 'str'。请参阅下面的 python 规则正文
- c# - 在 API 请求过程中使用并行 foreach?
- java - 使用 Java 制作 GUI 时从哪里开始(Swing 是否已弃用?)
- reactjs - 要使用 SmartCard 身份验证制作 React 应用程序,我应该使用 pkcs11 吗?
- jquery - 如何知道拖动了哪个类draggable
- excel - 函数问题:Excel VBA 中的日期过滤器
- c# - 如何在C#winform中使用相对地址读取文件
- rest - 为同一个 REST 资源混合不同的 2xx 响应代码
- c# - 与 C# 中的泛型参数混淆
- r - 预测和应用功能