Home > Back-end >  Removing last characters in a string with LINQ
Removing last characters in a string with LINQ

Time:01-11

I wanna read a file that eventually will be a matrix but I am bugged about a detail with this code below.

Text file looks like this:

[[15,7,18,11,19,10,14,16,8,2,3,6,5,1,17,12,9,4,13 
 [17,15,9,8,11,13,7,6,5,1,3,16,12,19,10,2,4,14,18],
  [...],
 [...]] // Ignore the new lines, in my text file is one single line. I did multiple lines here for readability


 

So the problem is that it ends with ]] and the end I get two empty list entries which is really bugging me. I wonder if I can remove them during projection, I tried using SkipLast() but the result empty. Any ideas?

 var readFile = File.ReadLines("RawTestcases.txt")
            .Select(x => x.Replace("[", string.Empty)
                          .Split("]"))
            .ToList();

Ok I actually just put the ]] on a new line and did a SkipLast(1) before projection, but can I do it if is one line?

CodePudding user response:

That looks like Json, so use the right tool:

string file = File.ReadAllText("RawTestcases.txt");
string[][] matrix = JsonConvert.DeserializeObject<string[][]>(file)
    .Where(array => array.Length > 0)
    .ToArray();

If you need them as integers you can directly use the right type:

int[][] matrix = JsonConvert.DeserializeObject<int[][]>(file)
    .Where(array => array.Length > 0)
    .ToArray();
  •  Tags:  
  • linq
  • Related