Ashiquzzaman
Ashiquzzaman

Reputation: 5284

How to convert Dictionary<string, object> to List<T>

I have a User class

public class  User
{
   public int Id { get; set; }
   public string Name { get; set; }
   public string Email { get; set; }    
}

and a Dictionary

public Dictionary<string, object> models = new Dictionary<string, object>
{
    {"Users[0].Id", 1},
    {"Users[0].Name", "Rajib"},
    {"Users[0].Email", "[email protected]"},
    {"Users[1].Id", 2},
    {"Users[1].Name", "Ashiq"},
    {"Users[1].Email", "[email protected]"},
    {"Users[2].Id", 3},
    {"Users[2].Name", "Zaman"},
    {"Users[2].Email", "[email protected]"},
};

Now I want to convert the value of Dictionary<string, object> models to List<User>. Can anyone suggest me how to do that?

Upvotes: 1

Views: 2808

Answers (2)

Ruben Vardanyan
Ruben Vardanyan

Reputation: 1308

Something like this will work for you.

var list = new List<User>();
for(var i = 0; i < models.Count/3; i++)
{
    var user = new User();
    user.Id = (int)models[string.Format("Users[{0}].Id", i)];
    user.Name = models[string.Format("Users[{0}].Name", i)].ToString();
    user.Email = models[string.Format("Users[{0}].Email", i)].ToString();
    list.Add(user);
}

But it is really strange to have this kind of Dictionary

Upvotes: 1

Gilad Green
Gilad Green

Reputation: 37299

It is strange what you wanna do and I think you should rethink your design. Maybe you can do something differently with how you construct your data... But this is how you can achieve it:

Group your data by the first part of the key, indicating a different User then project for each group a different User object. You can use reflection to assign the value to each correct property

var data = models.GroupBy(item => item.Key.Substring(0, item.Key.IndexOf(".")))
      .Select(group => group.Aggregate(new User(), (user, item) =>
      {
          PropertyInfo propertyInfo = user.GetType().GetProperty(item.Key.Substring(item.Key.IndexOf(".") + 1));
          propertyInfo.SetValue(user, Convert.ChangeType(item.Value, propertyInfo.PropertyType), null);
          return user;
      })).ToList();

Upvotes: 4

Related Questions