Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best wayto add single element to an IEnumerable collection?

I'm surprised to see that there does not appear to be a method to add a single element to an IEnumerable collection.

How can I add a single element to an IEnumerable collection?

like image 633
Vivian River Avatar asked Nov 15 '10 22:11

Vivian River


People also ask

How can I add an item to a IEnumerable T collection?

You cannot, because IEnumerable<T> does not necessarily represent a collection to which items can be added. In fact, it does not necessarily represent a collection at all! For example: IEnumerable<string> ReadLines() { string s; do { s = Console.

Can we add item in IEnumerable?

you can't add item to them directly and you should add the item to it's underlying source instead. IEnumerable<string> stringcol = new IEnumerable<string>(); stringcol = stringcol.

How do I get an IEnumerable element?

We can get first item values from IEnumerable list by using First() property or loop through the list to get respective element. IEnumerable list is a base for all collections and its having ability to loop through the collection by using current property, MoveNext and Reset methods in c#, vb.net.

How do you compare IEnumerable?

The SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) method enumerates the two source sequences in parallel and compares corresponding elements by using the default equality comparer for TSource , Default. The default equality comparer, Default, is used to compare values of the types.


2 Answers

You can't really add elements to an IEnumerable as it's supposed to be read only. Your best bet is either something like:

return new List<Foo>(enumerable){ new Foo() };

or

return enumerable.Concat(new [] { new Foo() });
like image 64
jonnii Avatar answered Sep 19 '22 17:09

jonnii


The point of IEnumerable is that it's a readonly pull style collection. If you want, you can simulate an add by doing something like this:

public static IEnumerable<T> Add<T>(this IEnumerable<T> source, T additionalItem)
{
   foreach(var item in source)
   {
      yield return item;
   }

   yield return additionalItem;
}
like image 23
BFree Avatar answered Sep 18 '22 17:09

BFree