Search code examples
c#stringconcatenationaggregate

Concatenate a range of a List<string>


If I have a List<string>, and I want to create a single string from all elements in the list, I can use either Join or Aggregate like below to accomplish that.

var list = new List<string>() { "A", "B", "C", "D", "E" };
var concatAllByJoin = string.Join(string.Empty, list);
var concatAllByAggregate = list.Aggregate((a, b) => a + b);

Either will produce the string ABCDE.

What if I want to do the same, but only for a certain range in the list. Say, I want to concatenate items between indices 1 and 3 inclusive. In other words, I want the result to be BCD.

One approach I can think of is using GetRange() like so:

var concatRange = string.Join(string.Empty, list.GetRange(1, 3));

This obviously works, but the problem is data duplication. I'm interested in knowing if there's a way to do this without the duplication.


Solution

  • If you do this:

    var concatRange = string.Join(string.Empty, list.Skip(1).Take(3));
    

    you will not create another list instance. But for small sets I think you'll find the extra list is not as costly and probably much more efficient than the enumerators. Remember, the list elements only store references, so the string values themselves are not copied with either option.