0

I tried to delete lines more than 35 characters but I'm getting this error:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'string[]'. An explicit conversion exists (are you missing a cast?)

and I don't know how to fix it. Can anyone help me?

My code:

            var lines = File.ReadAllLines("my path");
            lines = lines.Where(x => x.Length <= 35); // error is here
            File.Delete("my path");
            File.AppendAllLines("my path", lines);
Useme Alehosaini
  • 2,998
  • 6
  • 18
  • 26
Irkar
  • 11
  • Hover over `Where` in your code and inspect the return type. Notice that it's different than the type of `lines`. – gunr2171 Dec 20 '20 at 04:03
  • Does this answer your question? [Best way to convert IList or IEnumerable to Array](https://stackoverflow.com/questions/268671/best-way-to-convert-ilist-or-ienumerable-to-array) – gunr2171 Dec 20 '20 at 04:04
  • before send your question search the currect problem , don't search and tell your story . – hossein andarkhora Dec 20 '20 at 06:37

2 Answers2

1

When you read a file with .ReadAllLines(), you get an instance of String Array (string[]). When you use .Where() method, you get an IEnumerable<string> ... which cannot be assigned to a string array.

Simple solution would be to use .ToArray() to convert the result to a string array so you can assign it back to lines variable.

lines = lines.Where(x => x.Length <= 35).ToArray();
Jawad
  • 11,028
  • 3
  • 24
  • 37
0

The explanation of Jawad is on point. Note that there is another solution:

string[] lines = File.ReadAllLines("my path");
IEnumerable<string> lines2 = lines.Where(x => x.Length <= 35); // error is here
File.Delete("my path");
File.AppendAllLines("my path", lines2);

(I'm using string[] and IEnumerable<string> to make clear the types returned by the methods). File.AppendAllLines accepts as a parameter a IEnumerable<string>, so you can pass to it the result of the Where without transforming it first to an array. Note that I had to introduce a new lines2 variable.

xanatos
  • 109,618
  • 12
  • 197
  • 280