我如何使用 linq 附加到每个项目的 stringbuilder
我有一个 stringbuilder
Stringbuilder b = new StringBuilder();
,我想获取一个集合并使用 LINQ 附加集合中每个项目的属性名称。这可能吗?
像这样的东西:(
myCollection.Select(r=> b.Append(r.PropertyName);
但这似乎不起作用)
i have a stringbuilder
Stringbuilder b = new StringBuilder();
and i want to take a collection and append a propertyname from every item in the collection using LINQ. Is this possible.
something like this:
myCollection.Select(r=> b.Append(r.PropertyName);
(but this doesn't seem to work)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这将起作用(尽管这是一种非常迂回的做事方式)并且适用于任何
IEnumerable
:适应您的示例:
This would work (even though it's a very round-about way of doing things) and would work on any
IEnumerable<string>
:Adapted to your example:
当一个简单的 foreach 语句就足够具有表现力和简洁性时,您不需要在这里强制使用 LINQ 来解决这个问题。但是,如果您想使用更多功能式方法,您总是可以选择更像
string.Join
的东西,我相信它在内部使用StringBuilder
(但不引用我的话)。 但实际上,在您可能看到的所有示例中,它们会比 更简洁(或更易读)吗
?
You don't need to force the issue here with using LINQ when a simple foreach statement will be plenty expressive and concise enough. However, if you want to use more functional-esque approach, you can always go for something more like
string.Join
which I believe uses aStringBuilder
internally (but don't quote me on it). Such asBut really, of all the examples you might see, will they be any less verbose (or more readable) than
?
我会将其写为:
String.Concat(myCollection.Select(r => r.PropertyName));
I would write it as:
String.Concat(myCollection.Select(r => r.PropertyName));
有些集合支持“Each”扩展方法:
编辑:再看一下,也许这不是开箱即用的。我正在考虑 List<> 上的“ForEach”方法班级。无论如何,您可以非常轻松地编写自己的 Each 方法:
Some collections support an "Each" extension method:
EDIT: on second look, maybe this isn't provided out of the box. I was thinking of the "ForEach" method on the List<> class. Anyway, you can write your own Each method pretty easily: