Intersperse a 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?


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();

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 .


       public  List<string> GetNewList(List<string> list, string s)
    {
        var result = new List<string>();
        foreach (var l in list)
        {
            result.Add(l);
            result.Add(s);
        }
        result.RemoveAt(result.Count - 1);
        return result;
    }

您可以使用此方法获取您的列表

var result =   GetNewList(str,"-");
链接地址: http://www.djcxy.com/p/54864.html

上一篇: VS2010中是否有针对C#.NET的并发调试工具?

下一篇: 分散列表<>