使用linq聚合函数构建xml字符串?
我过去用它来构建逗号分隔的列表:
var list = new List<int>{1,2,3};
var retVal = list.Select(i=>i.ToString()).Aggregate((a,b) => a+", "+b);
效果很好。
我正在尝试做同样的事情来将每个元素“包装”为 xml 节点。
类似的东西:
Aggregate((a, b) => string.Format("<ID>{0}</ID><ID>{1}</ID>", a,b))
不过似乎不太能使其发挥作用。是否可以?或者有更简单的方法吗?
谢谢。
I've used this in the past to build comma seperated lists:
var list = new List<int>{1,2,3};
var retVal = list.Select(i=>i.ToString()).Aggregate((a,b) => a+", "+b);
Works great.
I'm trying to do the same sort of thing to 'wrap' each element as an xml node.
Something like:
Aggregate((a, b) => string.Format("<ID>{0}</ID><ID>{1}</ID>", a,b))
Can't quite seem to make it work though. Is it possible? Or is there an easier way entirely?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Blindy 的答案肯定会起作用,但我个人会使用:
我个人发现这比聚合更容易阅读和理解。我相信它也会更高效——尽管这只对大型列表很重要。
Blindy's answer will certainly work, but I'd personally use:
I personally find that easier to read and understand than the aggregation. I believe it will be more efficient, too - although that will only matter for large lists.
难道不应该是这样的:
您正在添加一个新节点。
Shouldn't it be like:
You're adding to
a
new nodes.有很多方法可以实现这一目标,但我怀疑正确的答案是“视情况而定”。创建 CSV 字符串的原始示例使用字符串连接运算符;推荐的方法是使用 StringBuilder 类来实现此目的。在 .Net 4.0 中,string.Join() 方法有一个新的重载,该方法更易于使用和理解。
如果您的目的是创建 XML 文档而不是字符串,则 David B 上面的答案是一个不错的选择:
对于创建 XML 字符串,我更喜欢避免显式编码开始和结束标记。在您的示例中,很难在开始或结束标记中使元素名称“ID”不正确,但我根据 DRY 原则来考虑这一点。有时,当我修改了配置文件中的开始标签时,我忘记修改元素的结束标签。使用XElement完全避免了这个问题:
Aggregate()与string.Join()、string.Join()的性能对比em> 每次都会获胜(使用我使用的相当有限/基本的测试用例)。
There are a number of ways to achieve this but I suspect the correct answer is "it depends". Your original example for creating a CSV string uses the string concatenation operator; the recommended approach is to use the StringBuilder class for this purpose. And in .Net 4.0 there is a new overload for the string.Join() method that is a whole lot simpler to use and understand.
If your intention is to create an XML Document rather than a string then David B's answer above is a good option:
For creating XML strings I prefer to avoid explicitly coding opening and closing tags. In your example it would be difficult to get the element name "ID" incorrect in either opening or closing tags but I think of this in terms of the DRY principle. On occasion I have forgotten to modify the closing tag for an element when I have modified the opening tag e.g. in config files. Using XElement avoids this issue completely:
Performance of Aggregate() versus string.Join(), string.Join() wins every time (with the fairly limited/basic test case I used).