'how to convert a model object to an IEnumerable

i have the following query that gets data regarding a vessel as follows

     public async Task<ExcelListModel>HandleAsync(VesselCrewQuery query)
     {  
       var test= await _queryDispatcher.DispatchAsync<FetchByIdQuery, VesselModel>(new FetchByIdQuery() { Id=query.vesselId});
       eModel = await generateExcel(test, lineItems,hint);
     }

i want to pass the above test variable into generateExcel file.

 public async Task<ExcelListModel> generateExcel(dynamic header,dynamic lines, string[][] fieldHints = null)
        {

            var HeaderlistModContent = new List<Dictionary<string, string>>();

            // when i get here (IEnumerable) header; it throws an error 
            var Headerlist =(IEnumerable) header;
            foreach (var item in Headerlist)
            {
                var HeaderModContent = new Dictionary<string, string>();
                var HeaderProperty = item.GetType().GetProperties();
                foreach (var prop in HeaderProperty)
                {
                    var name = prop.Name.ToString();
                    var value = GetPropertyValue(item, name).ToString();
                    HeaderModContent.Add(name, value);
                }
                HeaderlistModContent.Add(HeaderModContent);
            }
}


public static object GetPropertyValue(object source, string propertyName)
        {
            PropertyInfo property = source.GetType().GetProperty(propertyName);
            return property.GetValue(source, null);
        }

i want to pass the test variable so that i can extract the headings as above.But i get the following error **Unable to cast object of type 'VesselModel' to type 'System.Collections.IEnumerable'.**

i tried to change it as follows

var test= await _queryDispatcher.DispatchAsync<FetchByIdQuery,List< VesselModel>>(new FetchByIdQuery() { Id=query.vesselId});

but i still get the same error



Solution 1:[1]

By signature the return type of the method DispatchAsync is VeselModel:

 var test= await _queryDispatcher.DispatchAsync<FetchByIdQuery, VesselModel>(new FetchByIdQuery() { Id=query.vesselId});

It hints that VesselModel could be a single instance (not a collection). It's even indicated by FetchByIdQuery; usually, you should get a single item by Id. Even error message hints that it's not a collection.

So, you are passing a single instance to generateExcel as the parameter dynamic header. And a single instance can't be cast to IEnumerable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Karlis Fersters