Home > Software engineering >  Convert List<IDictionary<string, string>> to strongly typed list in C#
Convert List<IDictionary<string, string>> to strongly typed list in C#

Time:04-15

Using C#, I have the following list using IDictionary:

List<IDictionary<string, string>> lstDictionary;

After I populate the list above, I need to convert it to a strongly typed list based on a class:

public class customer
    {
        public string FirstName{ get; set; }
        public string LastName{ get; set; }
        public string Status{ get; set; }
    }
List<customer> lstCustomers;

So now, I am trying to convert using LAMBDA/LINQ but not working (Shows error message on p.FirstName):

lstCustomers = lstDictionary.Select(p => new customer
            {
                FirstName = p.FirstName,
                LastName = p.LastName,
                Status = p.Status
            }).ToList();

Any help would be appreciated.

CodePudding user response:

Remember, each p in the call to Select is an IDictionary<string, string>. In .Net you use an indexer to access elements in a Dictionary; there is no p.FirstName, but there might be a p["FirstName"].

So assuming the keys are always setup correctly it will look like this:

lstCustomers = lstDictionary.Select(p => new customer
        {
            FirstName = p["FirstName"],
            LastName = p["LastName"],
            Status = p["Status"]
        }).ToList();

Finally, I need to point out the "might" in my first paragraph. This has the potential to blow up at runtime if the Dictionary ends up with unexpected data. In the .Net world this is considered poor design and is usually the result of mistake made earlier. Sometimes you're far enough down the line you push on anyway, but the mistake is still there.

  • Related