How to convert var to string []

I wrote 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 goes on the last line, where the following errors occur:

  • System.Collections.Generic.IEnumerable<AnonymousType#1> does not contain a definition for ToArray and the best extension method; overloading 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 how to convert my var to string[] ?

+6
source share
1 answer

Here you create an anonymous type:

 new { Node = line.Trim() } 

This is optional, just return

 line.Trim() 

and you have 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 variant:

 possibleElements.Select(x => x.Node).ToArray(); 
+12
source

Source: https://habr.com/ru/post/987483/


All Articles