tags:

views:

378

answers:

6

For example:

string element = 'a';
IEnumerable<string> list = new List<string>{ 'b', 'c', 'd' };

IEnumerable<string> singleList = ???; //singleList yields 'a', 'b', 'c', 'd'
+8  A: 

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");
Marc Gravell
+1. But :( for the Java style brackets!
Dead account
Richard
Shouldn't that be Concat() instead of Union()? Union() returns only distinct elements.
Lucas
There was a typo: use Concat, not Union
jyoung
OK - Concat has it
Marc Gravell
@Ian - I use that style of braces on forums to preserve vertical space. For actual code, I honestly don't care what the brace style is.
Marc Gravell
+1  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.

Anton Gogolev
If you make this an extension method, You just implemented IEnumerable<T>.Union() :P
Lucas
errr i mean Concat()
Lucas
+2  A: 

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);
jalf
+1  A: 
public static class IEnumerableExtensions
{
    public static IEnumerable<T> Prepend<T>(this IEnumerable<T> ie, T item)
    {
         return new T[] { item }.Concat(ie);
    }
}
BFree
Looks to me like you are concating the item to the end, not prepending it...
Josh G
Oops, good point. I'll edit...
BFree
+1  A: 

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.

Martin Peck
In your second example, singleList is an IEnumerable, not a List.
Lucas
A: 

Also:

IEnumerable<string> items = Enumerable.Repeat(item, 1).Concat(list);
Josh G