Home > OS >  Convert a for loop to linq
Convert a for loop to linq

Time:03-09

I have a simple for loop but I want to convert it to Linq and return empty Dict. if object is null. I have not used it before. Can anyone help me out on this ?

private Dictionary<string, class1> getInfo(IEnumerable<class2> infos)
{
     Dictionary<string, class1> trs = new();
     if (infos is null)
         return trs;

     //This loop I want to convert to linq
     for(class2 info in infos)
     {
        class1 tr = new()
        {
            bi = info.bi,
            state = bi.State,
            res = Enum.value;
        };   
        trs.Add(info.value1, tr);
     }
     return trs;
}

CodePudding user response:

You can use .ToDictionary() to create a dictionary from IEnumerable<class2>

Dictionary<string, class1> trs = infos
     ?.ToDictionary(key => Key.value1, 
                   value => new class1() {
                              bi = value.bi,
                              state = bi.State,
                              res = Enum.value
                            }) ?? new Dictionary<string, class1>(); 

Free Advice : I highly recommend you to use proper naming conventions while declaring class and variables, this will make your code more readable and easy to understand

  • Related