0
votes

I am trying to identify ienumerable properties within an object and then convert it to Dictionary object

I wrote a linq query with lambda expression to convert list of list to list and I am following example from this msdn article

When I try to execute following program in LINQPad I am getting a compile time error

void Main()
{

       var list = new List<int>();
       list.Add(1);
       list.Add(2);

       var list2 = new List<string>();
       list2.Add("ab");
       list2.Add("xy");

       var obj = new { x = "hi", y = list, z = list2 , a =1};


       var properties = (obj.GetType()).GetProperties()
                                                     .Select(x => new {name =x.Name , value= x.GetValue(obj, null)})
                                                     .Where( x=> x.value != null && (x.value is IEnumerable) && x.value.GetType() != typeof(string) )
                                                     .Select(x => new {name = x.name, value= x.value});


       Console.WriteLine(properties);

       foreach( var item in properties)
       {
            var col = (IEnumerable) item.value;
            foreach ( var a in col)
            {
                Console.WriteLine("{0}-{1}",item.name,a);
            }
       }




       //compile time error in following line

       var abc = properties.SelectMany(prop => (IEnumerable )prop.value, (prop,propvalue) => new {prop,propvalue} )
                 .Select( propNameValue =>
                  new {
                    name = propNameValue.prop.name,
                    value = propNameValue.propvalue
                  }
                 );

        Console.WriteLine(abc);



}

The type arguments for method 'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable, System.Func>, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

How I can restructure SelectMany statement to get rid of the error so I can get output similar to nested foreach loop?

1

1 Answers

1
votes

I would like to simplify your problem, assume you have two list: listInt and listString

var listInt = new List<int> { 1, 2 };
var listString = new List<string> { "ab", "xy" };

then create a listObject like below:

var listObject = new object[] { listInt, listString };

If you do SelectMany:

var output = listObject.SelectMany(list => list);

You will get the same error with yours since two list contains different types. You would think to cast to IEnumerable<object> like:

var output = listObject.SelectMany(list => (IEnumerable<object>)list);

But it is not going to work for listInt since co-variant does not support value type. Just only solution I would think:

var output = listObject.SelectMany(list => ((IEnumerable)list).Cast<object>());

So, to map with your problem, you can change:

prop => ((IEnumerable)prop.value).Cast<object>();