Question

Is it possible to convert class as IEnumerable?

 private SeriesMapping CreateSeriesMapping(string category, string value, string stackKey, CustomObject itemsSource)
    {
        var data= (IEnumerable)itemsSource;
        SeriesMapping successMapping = new SeriesMapping() { SeriesDefinition = new StackedBar100SeriesDefinition() { StackGroupName = stackKey } };
        successMapping.ItemMappings.Add(new ItemMapping(category, DataPointMember.XCategory));
        successMapping.ItemMappings.Add(new ItemMapping(value, DataPointMember.YValue));
        successMapping.ItemsSource = data; // after conversion i did not any data.

     // successMapping.ItemsSource = itemsSource; //if i use this i did not get error But while opening the chart Null Reference exception is coming. 
        return successMapping;
    }

that's way i am thinking that class object....

Was it helpful?

Solution

If you want to create a single-element collection (your question is not very clear), you can simply use an array:

IEnumerable<CustomObject> data = new []{ itemsSource };   

OTHER TIPS

You have to derive from IEnumerable and implement it eventually. This is for cases when you need simply, say, foreach over your class instance like if it is a collection of items.

Implement IEnumerable.

Other way it just define this[key] (indexer) property on your class, so you will be able to use your instance like

itemsSource[SOME_KEY]

Using indexer in C#

Even if your question is not so clear, me too as @ehsan I can't understand what you want to accomplish, I think, starting from the only things you asked, the simplest way to do that is implementing the IEnumerable interface, better would be to implement the generic version IEnumerable<T> in that way you can enumerate over a well-known-type enumerator with all the advantages you can gain, eg. linq operators support without casting and more.

Another way to accomplish that, a more elegant way without implementing the whole interface at all, should be implementing the yield pattern , doing so you can provide a method which returns an enumerator IEnumerable<T> and in the method, inside a foreach loop, simply yield returning the current item, this will provide an enumerator support, without implementing the IEnumerable.

just for reference yield usage example & ref

So the simple answer is

  var enumerable = (IEnumerable)itemsSource;

But to give you a correct answer I should know the whole details about CustomObject.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top