Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast object to IEnumerable

object selectedDataItem;
MyClass.Inventory inventory;
inventory = (MyClass.Inventory) selectedDataItem;

in inventory we can see the details such as:

Trace.Writeline(inventory.Name + " " + inventory.Place);

You see inventory has inventory.Name, Inventory.Place I want to wrap all of the property inside IEnumerable or ObservableCollection so that I can iterate through all of the inventory at once and not by inventory.Name, inventory.Place etc etc...

How can I make inventory IEnumerable so that I can do something like this :

IEnumerable<MyClass.Inventory> enumerable = (IEnumerable<MyClass.Inventory>) inventory;
enumerable = from x in enumerable where x.Name == inventory.Name select x;

Right now if I do this the error is

Unable to cast object of type 'MyClass.Inventory' to type 'System.Collections.Generic.IEnumerable`1[MyClass.Inventory]'.

like image 293
momokjaaaaa Avatar asked Nov 29 '22 07:11

momokjaaaaa


2 Answers

Not sure why do you need this, but once i saw next extension method:

public static class CustomExtensions
{
    public static IEnumerable<T> ToEnumerable<T>(this T input)
    {
        yield return input;
    }
}
like image 43
Uriil Avatar answered Dec 12 '22 02:12

Uriil


Just do this:

var enumerable = new [] { inventory };
like image 71
Enigmativity Avatar answered Dec 12 '22 02:12

Enigmativity