加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何将var转换为string []

发布时间:2020-12-15 06:46:49 所属栏目:百科 来源:网络整理
导读:我在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[] xml
我在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>();

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

  • 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>

有什么问题以及将我的var转换为字符串[]的方法是什么?

解决方法

您在此处创建匿名类型:
new { Node = line.Trim() }

这不是必要的,只需返回

line.Trim()

你有一个IEnumerable字符串.然后你的ToArray将工作:

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

string[] xmlLines = possibleElements.ToArray();

另一种选择是:

possibleElements.Select(x => x.Node).ToArray();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读