-4

I have an array with items having names with .txt. I want to remove the extension. The following code is not working.

var xx = filenames.ForEach(x =>
{
    int fileExtPos = x.LastIndexOf(".");
    if (fileExtPos >= 0)
        x = x.Substring(0, fileExtPos);
});

Can anyone help what am i doing wrong here?

Thanks

maccettura
  • 10,514
  • 3
  • 28
  • 35
Mukil Deepthi
  • 6,072
  • 13
  • 71
  • 156
  • You can use Path.GetFileNameWithoutExtension("filename") – Murat Tüfekçi Sep 27 '18 at 13:23
  • `"The following code is not working."` -- Why is it not working? Is there an error? Are the results wrong? Also, in the future dont use the `.ForEach()` extension method. Use a `foreach` loop – maccettura Sep 27 '18 at 13:23
  • 1
    It would be awesome if you could provide a [mcve]. For example, I am surprised if the above code compiles if `filenames` is an array. Also, do you want the filenames (without extension) to be **written back** to the array? Or do you want to project that to a new list / array? Or something else? – mjwills Sep 27 '18 at 13:26
  • 2
    `var names = filenames.Select(Path.GetFileNameWithoutExtension);` – TVOHM Sep 27 '18 at 13:27

1 Answers1

6

There is a build in method GetFileNameWithoutExtension() which could be used. That's the common way to handle this.

var result = filenames.Select(System.IO.Path.GetFileNameWithoutExtension);

You error appears here var xx = filenames.ForEach because ForEach has no return value (void) which could be assigned to var xx.

fubo
  • 44,811
  • 17
  • 103
  • 137