Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert var to string[]

I have written a LINQ in C#

string etXML = File.ReadAllText("ET_Volume.xml");
string[] allLinesInAFile = etXML.Split('\n');

var possibleElements = from line in allLinesInAFile
                       where !this.IsNode(line)
                       select new { Node = line.Trim() };  

string[] xmlLines = possibleElements.ToArray<string>();

The problem is coming at last line, where the following errors arise:

  • System.Collections.Generic.IEnumerable<AnonymousType#1> does not contain a definition for ToArray and the best extension method overload System.Linq.Enumerable.ToArray<TSource>(System.Collections.Generic.IEnumerable<TSource>) has some invalid arguments

  • Instance argument: cannot convert from System.Collections.Generic.IEnumerable<AnonymousType#1> to System.Collections.Generic.IEnumerable<string>

What is wrong and what is the way to convert my var to a string[]?

like image 445
SimpleGuy Avatar asked May 19 '15 08:05

SimpleGuy


1 Answers

You are creating an anonymous type here:

new { Node = line.Trim() }

That isn't necessary, just return

line.Trim()

and you have an IEnumerable of string. Then your ToArray will work:

var possibleElements = from line in allLinesInAFile
                       where !this.IsNode(line)
                       select line.Trim();  

string[] xmlLines = possibleElements.ToArray();

Another option is:

possibleElements.Select(x => x.Node).ToArray();
like image 107
Patrick Hofman Avatar answered Sep 20 '22 09:09

Patrick Hofman