Fastest way to convert a list of strings into a single concatenated string?

后端 未结 7 2076
一向
一向 2021-02-14 21:27

I have some LINQ code that generates a list of strings, like this:

var data = from a in someOtherList
           orderby a
           select FunctionThatReturnsS         


        
相关标签:
7条回答
  • 2021-02-14 21:59

    Use "Aggregate" like this:

        List<string> strings = new List<string>() {"bob", "steve", "jane"};
        string result = strings.Aggregate((working, next) => working + next);
        Console.WriteLine(result);
    

    Note: Aggregate is in the System.Linq namespace as an extension method.

    0 讨论(0)
  • 2021-02-14 22:00

    Have you tried String.Join? If you're already willing to take the overhead of a .ToList call then instead use .ToArray() and combine it with a call to String.Join.

    var joined = String.Concat(someQuery.ToArray());
    

    Note: My solution is likely not the fastest as it involves a bit of overhead in the array. My suspicion is that it would be faster to go more Marc's route. But in most cases if you're just looking for the quick and dirty way to do it in code, my route will work.

    0 讨论(0)
  • 2021-02-14 22:00
    data.ToList().Aggregate(new StringBuilder(), (sb, s) => sb.Append(s)).ToString();
    
    0 讨论(0)
  • 2021-02-14 22:04

    You can use this statement. String.Join("",someOtherList);

    0 讨论(0)
  • 2021-02-14 22:17

    How about:

    public static string Concat(this IEnumerable<string> source) {
        StringBuilder sb = new StringBuilder();
        foreach(string s in source) {
            sb.Append(s);
        }
        return sb.ToString();
    }
    

    and:

    string s = data.Concat();
    

    This then has no need for the extra ToList() / ToArray() step.

    0 讨论(0)
  • 2021-02-14 22:19

    Alternative:

    >>> data = ['Some ', 'resulting ', 'data here.']
    >>> s = ''.join(data)
    >>> s
    'Some resulting data here.'
    
    0 讨论(0)
提交回复
热议问题