开发者

How do I use the Aggregate function to take a list of strings and output a single string separated by a space?

开发者 https://www.devze.com 2023-01-23 11:13 出处:网络
Here is the source code for this test: var tags = new List<string> {\"Portland\", \"Code\",\"StackExcahnge\" };

How do I use the Aggregate function to take a list of strings and output a single string separated by a space?

Here is the source code for this test:

    var tags = new List<string> {"Portland", "Code","StackExcahnge" };
    const string separator = " ";
    tagString = tags.Aggregate(t => , separator);
    Console.WriteLine(tagString);
    // Ex开发者_StackOverflow社区pecting to see "Portland Code StackExchange"
    Console.ReadKey();

Update

Here is the solution I am now using:

var tagString = string.Join(separator, tags.ToArray());

Turns out string.Join does what I need.


For that you can just use string.Join.


string result = tags.Aggregate((acc, s) => acc + separator + s);

or simply

string result = string.Join(separator, tags);


String.Join Method may be?


This is what I use

public static string Join(this IEnumerable<string> strings, string seperator)
{
    return string.Join(seperator, strings.ToArray());
}

And then it looks like this

tagString = tags.Join(" ")
0

精彩评论

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