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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With