Is there a common way to pass a single item of type T
to a method which expects an IEnumerable<T>
parameter? Language is C#, framework version 2.0.
Currently I am using a helper method (it's .Net 2.0, so I have a whole bunch of casting/projecting helper methods similar to LINQ), but this just seems silly:
public static class IEnumerableExt { // usage: IEnumerableExt.FromSingleItem(someObject); public static IEnumerable<T> FromSingleItem<T>(T item) { yield return item; } }
Other way would of course be to create and populate a List<T>
or an Array
and pass it instead of IEnumerable<T>
.
[Edit] As an extension method it might be named:
public static class IEnumerableExt { // usage: someObject.SingleItemAsEnumerable(); public static IEnumerable<T> SingleItemAsEnumerable<T>(this T item) { yield return item; } }
Am I missing something here?
[Edit2] We found someObject.Yield()
(as @Peter suggested in the comments below) to be the best name for this extension method, mainly for brevity, so here it is along with the XML comment if anyone wants to grab it:
public static class IEnumerableExt { /// <summary> /// Wraps this object instance into an IEnumerable<T> /// consisting of a single item. /// </summary> /// <typeparam name="T"> Type of the object. </typeparam> /// <param name="item"> The instance that will be wrapped. </param> /// <returns> An IEnumerable<T> consisting of a single item. </returns> public static IEnumerable<T> Yield<T>(this T item) { yield return item; } }
What you can do is use the Add extension method to create a new IEnumerable<T> with the added value. var items = new string[]{"foo"}; var temp = items; items = items. Add("bar");
Background Topics - IEnumerable<T> That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!
As far as I know List<T> implements IEnumerable<T> . It means that you do not have to convert or cast anything. It depends. If you try to set a IEnumerable<IList<obj>> to an IEnumerable<IEnumerable<obj>> it gives a compiler error since the second does not inherit from the first one.
Well, if the method expects an IEnumerable
you've got to pass something that is a list, even if it contains one element only.
passing
new[] { item }
as the argument should be enough I think
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