Search code examples
c#linqindexoutofboundsexception

Grouping with LINQ in C# - Index out of bounds


I'm trying to group the strings according to their extension (last three characters) to train my LINQ skills (I'm a newbie), but I keep getting an exception:

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

My code is bellow: Where is my mistake?

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);
}

Solution

  • As jdweng mentioned on comment section. You just need to use overload of 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);
    }
    

    Result would be:

    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