-1

I have a structure defined

public class FullIndexList
{
    public IList<IndexCurrency> IndexCurrency { get; set; }

    public IList<Indices> Indices { get; set; }
 }

The List returned from the method

So basically the list items are properties FullIndexList ,the type is List`1

I want to convert the result to FullIndexList.

I have tried using cast as results.Cast() it givens error as invalid cast, I have also tried using results.ConvertAll but in that case I need to hard code like this

fullIndexList.IndexCurrency = results[0] as IList<IndexCurrency>;
fullIndexList.Indices = results[1] as IList<Indices>;

which does not looks right.

I can think of using Reflection or Automapper but I believe there might be a better way of doing this.

Rahul
  • 1
  • 3

2 Answers2

0

This makes your result flat and then find the type to make IList.

var flat = results.OfType<IEnumerable<object>>().SelectMany((x) => x).ToArray();
fullIndexList.IndexCurrency = flat.OfType<IndexCurrency>().ToList();
fullIndexList.Indices = flat.OfType<Indices>().ToList();

Your results is List<dynamic> so need to cast it to IEnumerable<object> or any other common base class or interface. This means if your IndexCurrency or Indices is struct, it's difficult. Struct cannot be casted directly to object. Why cannot IEnumerable<struct> be cast as IEnumerable<object>?

If you can make results not to use dynamic, it becomes very easy because you can directly make it flat by SelectMany().

Community
  • 1
  • 1
cactuaroid
  • 496
  • 1
  • 4
  • 19
  • Error 26 The type arguments for method 'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable, System.Func>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. – Rahul Oct 21 '16 at 09:20
  • @Rahul What is the type of `results`, `results[0]` and `results[1]`? I assumed they are `List>` and `List` type. – cactuaroid Oct 21 '16 at 16:23
  • result is List`1 and results[0] List , results[1] List – Rahul Oct 21 '16 at 17:10
  • @Rahul Oh you mean `results` is `List` type. `IndexCurrency` and `Indices` are class or struct? – cactuaroid Oct 21 '16 at 20:44
0

I was able to get it done using zip and tupple.

foreach (var tuple in typeof(FullIndexList).GetProperties().Zip(results, Tuple.Create))
{
   tuple.Item1.SetValue(full, tuple.Item2, null);
}

where FullIndexList is the container type.

However I am not performing any check and assuming the order and no of items in both list are exactly same.

Rahul
  • 1
  • 3