How to bind different values from a list into another list on the bases of Key using Linq

37 Views Asked by At

I am working on application where I am receiving data shown in demo list below.

var dd = new List<ConfigurationItem> {

     new ConfigurationItem { 
 Key = "Partners:JohnDeere:Manufacturers:0:ManufacturerIdentity", 
 Value= "13" 
                           }
,
     new ConfigurationItem {
 Key = "Partners:JohnDeere:Manufacturers:1:ManufacturerIdentity", 
 Value= "14" 
                      },

new ConfigurationItem {
 Key = "Partners:JohnDeere:Manufacturers:0:SubmitLocator",
 Value= "True" 
                      },

new ConfigurationItem {
 Key = "Partners:JohnDeere:Manufacturers:1:SubmitLocator",
 Value= "True"
                     },
                };

What I am trying to achieve to assign this information to another list manufacturerOptions on the bases of Key. This is Option Patterns used in hear. Here is my code

      public class ManufacturerOptions 
        {
      
            public int ManufacturerIdentity { get; set; }
    
            public int LocationIdentity { get; set; } 
    
            public bool SubmitLocator { get; set; }
    
            public string WarehouseType { get; set; }
    
            public string WarehouseCode { get; set; }
        }

Method Code


 _dataTransferFacilityOptions.Manufacturers = 
 dd.Where(x => x.Key.Contains("ManufacturerIdentity") )
.Select(x => new ManufacturerOptions  {
                        ManufacturerIdentity = Convert.ToInt32(x.Value)
    
                }).ToList();

Here I am binding ManufacturerIdentity but I need to bind other values too like SubmitLocator but here I am only binding one ManufacturerIdentity. I need to convert the list into ManufactureOptions List.

1

There are 1 best solutions below

0
abolfazl  sadeghi On

I noticed something, you also want to set the field SubmitLocator .You Can Use this code for this

 _dataTransferFacilityOptions.Manufacturers =
                dd.Where(x => x.Key.Contains("ManufacturerIdentity") 
                             || x.Key.Contains("SubmitLocator"))
                .Select(x => new ManufacturerOptions
                {
                    ManufacturerIdentity = (!x.Key.Contains("ManufacturerIdentity") ?
                 null /*or Default For Not null*/ : Convert.ToInt32(x.Value)),

                    SubmitLocator = (!x.Key.Contains("SubmitLocator") ? 
                      null /*or Default For Not null*/ : Convert.ToBoolean(x.Value))

                   ,

                }).ToList();

Due to these fields, other values cannot be entered. You must set the fields to null

 public class ManufacturerOptions
    {

        public int? ManufacturerIdentity { get; set; }

        public int? LocationIdentity { get; set; }

        public bool? SubmitLocator { get; set; }

        public string? WarehouseType { get; set; }

        public string? WarehouseCode { get; set; }
    }