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>
什么是错的,什么是我的转换方法var
为string[]
?
Pat*_*man 12
您在此处创建匿名类型:
new { Node = line.Trim() }
Run Code Online (Sandbox Code Playgroud)
这不是必要的,只需返回
line.Trim()
Run Code Online (Sandbox Code Playgroud)
和你有一个IEnumerable
的string
.然后你的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)