Rahul Rahul - 10 months ago 73
C# Question

Mapping List`1 to Object properties

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.

Answer Source

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.