如何将var转换为string []

Sim*_*Guy 6 .net c# linq generics

我在C#中写了一个LINQ

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>();
Run Code Online (Sandbox Code Playgroud)

问题出现在最后一行,出现以下错误:

  • System.Collections.Generic.IEnumerable<AnonymousType#1>不包含定义,ToArray并且最好的扩展方法重载 System.Linq.Enumerable.ToArray<TSource>(System.Collections.Generic.IEnumerable<TSource>) 有一些无效的参数

  • 实例参数:无法转换System.Collections.Generic.IEnumerable<AnonymousType#1>System.Collections.Generic.IEnumerable<string>

什么是错的,什么是我的转换方法varstring[]

Pat*_*man 12

您在此处创建匿名类型:

new { Node = line.Trim() }
Run Code Online (Sandbox Code Playgroud)

这不是必要的,只需返回

line.Trim()
Run Code Online (Sandbox Code Playgroud)

和你有一个IEnumerablestring.然后你的ToArray意志工作:

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

string[] xmlLines = possibleElements.ToArray();
Run Code Online (Sandbox Code Playgroud)

另一种选择是:

possibleElements.Select(x => x.Node).ToArray();
Run Code Online (Sandbox Code Playgroud)

  • @SimpleGuy如果你想深入了解LINQ在幕后做什么(并且有很多时间;-)),你应该看看Jon Skeet的优秀[Edulinq系列](http://codeblog.jonskeet.uk/category/ edulinq) (3认同)