Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersperse a List<> [duplicate]

Tags:

c#

list

Possible Duplicate:
Extension method for Enumerable.Intersperse?

I have a List<string> like this:

"foo", "bar", "cat"

I want it to look like this:

"foo", "-", "bar", "-", "cat"

Is there a C# method that does that?

like image 547
fasss Avatar asked Sep 15 '11 11:09

fasss


2 Answers

You can make an extension that returns an IEnumerable<T> with interspersed items:

public static class ListExtensions {

  public static IEnumerable<T> Intersperse<T>(this IEnumerable<T> items, T separator) {
    bool first = true;
    foreach (T item in items) {
      if (first) {
        first = false;
      } else {
        yield return separator;
      }
      yield return item;
    }
  }

}

The advantage of this is that you don't have to clutter your list with the extra items, you can just use it as it is returned:

List<string> words = new List<string>() { "foo", "bar", "cat" };

foreach (string s in words.Intersperse("-")) {
  Console.WriteLine(s);
}

You can of course get the result as a list if you need that:

words = words.Intersperse("-").ToList();
like image 180
Guffa Avatar answered Sep 30 '22 03:09

Guffa


Here is an implementation out of my personal toolbox. It's more general than what you require.

For your particular example, you would write

var list = new List<string> { "foo", "bar", "cat" };
var result = list.InterleaveWith(Enumerable.Repeat("-", list.Count - 1));

See it in action.

like image 24
Jon Avatar answered Sep 30 '22 05:09

Jon