For example:
string element = 'a';
IEnumerable<string> list = new List<string>{ 'b', 'c', 'd' };
IEnumerable<string> singleList = ???; //singleList yields 'a', 'b', 'c', 'd'
For example:
string element = 'a';
IEnumerable<string> list = new List<string>{ 'b', 'c', 'd' };
IEnumerable<string> singleList = ???; //singleList yields 'a', 'b', 'c', 'd'
I take it you can't just Insert
into the existing list?
Well, you could use new[] {element}.Concat(list)
.
Otherwise, you could write your own extension method:
public static IEnumerable<T> Prepend<T>(
this IEnumerable<T> values, T value) {
yield return value;
foreach (T item in values) {
yield return item;
}
}
...
var singleList = list.Prepend("a");
No, there's no such built-in statment, statement, but it's trivial to implement such function:
IEnumerable<T> PrependTo<T>(IEnumerable<T> underlyingEnumerable, params T[] values)
{
foreach(T value in values)
yield return value;
foreach(T value in underlyingEnumerable)
yield return value;
}
IEnumerable<string> singleList = PrependTo(list, element);
You can even make it an extension method if C# version allows for.
You can roll your own:
IEnumerable<T> Prepend<T>(this IEnumerable<T> seq, T val) {
yield return val;
foreach (T t in seq) {
yield return seq;
}
}
And then use it:
IEnumerable<string> singleList = list.Prepend(element);
public static class IEnumerableExtensions
{
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> ie, T item)
{
return new T[] { item }.Concat(ie);
}
}
This would do it...
IEnumerable<string> singleList = new[] {element}.Concat(list);
If you wanted the singleList to be a List then...
IEnumerable<string> singleList = new List<string>() {element}.Concat(list);
... works too.
Also:
IEnumerable<string> items = Enumerable.Repeat(item, 1).Concat(list);