Home > OS >  Use LINQ to convert List of Dictionary to strongly Typed Class object List
Use LINQ to convert List of Dictionary to strongly Typed Class object List

Time:06-09

I am working on .NET CORE 6 app and I have Dictionary with structured as

 Dictionary<string, Dictionary<int, string>> dataDictionary

I have pull list of Dictionary based on List<Dictionary<int, string>> filteredDictionary as below

var filteredDictionary = dataDictionary.Values.ToList();

Each list has 17 dictionary that represent properties of class AIMSchema where each property is represented by key (Int) no. So I know value at dictionary index 0 present TransactionDate, 1 represent MachineCode and so on... The object is I want convert this dictionary list to List<AIMSchema>

I can do in loop as below but I want to do using LINQ

foreach (var schema in dataDictionary.Values)
 {
    if(schema != null)
       {
          var aimSchema = new AIMSchema
          {
              TransactionDate = schema[0],
              MachineCode = schema[1],
              // ... other properties
          }
        }

CodePudding user response:

Well, I'm going to provide exactly what you asked for as an answer. The LINQ equivalent of your existing code would look like this:

List<AIMSchema> result = dataDictionary.Values
    .Where(schema => schema != null)
    .Select(schema => new AIMSchema
    {
        TransactionDate = schema[0],
        MachineCode = schema[1],
        // ... other properties
    })
    .ToList();

The .Where is a filter, equivalent to your if (schema != null), and the .Select is a projection which turns the entry into an AIMSchema object. As we're still dealing with a query on dataDictionary.Values at this stage, the .ToList() materializes the result into a List<AIMSchema>.

  • Related