开发者

how can i append to a stringbuilder on every item usinq linq

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)


This would work (even though it's a very round-about way of doing things) and would work on any IEnumerable<string>:

List<string> foo = new List<string>();
foo.Add("bar");
foo.Add("baz");
StringBuilder result = foo.Aggregate(new StringBuilder(), (a, b) => a.Append(b)); 

Adapted to your example:

StringBuilder result = myCollection.Aggregate(new StringBuilder(), (a, b) => a.Append(b.PropertyName)); 


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 a StringBuilder internally (but don't quote me on it). Such as

builder.Append(string.Join("", myCollection.Select(r => r.PropertyName)));

But really, of all the examples you might see, will they be any less verbose (or more readable) than

foreach (var item in myCollection) 
     builder.Append(item.PropertyName);

?


I would write it as:

String.Concat(myCollection.Select(r => r.PropertyName));


Some collections support an "Each" extension method:

myCollection.Each(r => b.Append(r.PropertyName));

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:

public static void Each<T>(this IEnumerable<T> items, Action<T> action)
{
    if (items == null) return;

    var cached = items;

    foreach (var item in cached)
        action(item);
}


        List<string> words = new List<string>()
        { 
        "aaa",
        "aab",
        "aac",
        "aad",
        };

        StringBuilder sb = new StringBuilder();
        words.ForEach(a => sb.AppendFormat("Element {0}\n",a));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜