Home > database >  Advise to optimize the following code in a better way
Advise to optimize the following code in a better way

Time:10-20

I have some data stored in a dictionary where the values are basically a list of objects with few attributes in them. Right now I'm looping through as following to get the data stored in a specific attribute. These data are then added into a drop down list (unity UI dropdown)

foreach (KeyValuePair<string, List<NameIDValuePair>> kvp in TeamValuePair)
            {
                List<NameIDValuePair> list = kvp.Value;

                if(kvp.Key == teamNames.options[teamNames.value].text)
                {
                    foreach (var rec in list)
                    {
                        screenNamesDropDown.options.Add(new TMP_Dropdown.OptionData { text = rec.ScreenName });
                    }
                }
            }

teamNames and screenNamesDropDown are dropdown elements part of my unity UI.

The structure of the NameIdValuePair looks as follows:

public class NameIdValuePair 
        {
            public string ScreenName { get; private set; }

            public string ScreenId { get; private set; }
        }

I would like to optimize this piece of code in a better way using linq - so that it's a bit more readable. Since I'm pretty new to linq, i'm not really sure if I'm using the right keywords when searching for suggestions but so far I haven't had much success in finding any helpful suggestion.

Thanks

CodePudding user response:

As mentioned before instead of looping a Dictionary - where we already know that the keys are unique - you could simply use Dictionary.TryGetValue

// do this only once! 
var key = teamNames.options[teamNames.value].text;

if (TeamValuePair.TryGetValue(key, out var list))
{
    foreach(var item in list)
    {
        screenNamesDropDown.options.Add(new TMP_Dropdown.OptionData(item.ScreenName));
    }
}

and then actually the only place where you could use Linq if you really want to would maybe be in

var key = teamNames.options[teamNames.value].text;

if (TeamValuePair.TryGetValue(key, out var list))
{
    screenNamesDropDown.options.AddRange(list.Select(item => new TMP_Dropdown.OptionData(item.ScreenName)));
}

if this makes it better to read is questionable though.

And in general the question would also be if you always want to Add (AddRange) to the screenNamesDropDown.options or if you maybe want to actually replace the options. Then instead of AddRange you could do

screenNamesDropDown.options = list.Select(item => new TMP_Dropdown.OptionData(item.ScreenName)).ToList();
  • Related