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?
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.
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.
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.
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.
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() });
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;
}
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