简体   繁体   中英

Use LINQ to convert List of Dictionary to strongly Typed Class object List

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
          }
        }

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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM