Home > Software engineering >  How to get first element from Value List of a Dictionary?
How to get first element from Value List of a Dictionary?

Time:03-02

I have the following declaration and I need to get the first element from the list using key. Then after assigning that value to some variable again I need to remove that value alone from that list.

Dictionary<string, List<string>> data = new Dictionary<string, List<string>>();

For Example:

List<string> teamMembers = new List<string>();
teamMembers.Add("Country1Player1");
teamMembers.Add("Country1Player2");
teamMembers.Add("Country1Player3");
data.Add("Country1",teamMembers);
teamMembers = new List<string>();
teamMembers.Add("Country2Player1");
teamMembers.Add("Country2Player2");
teamMembers.Add("Country2Player3");
data.Add("Country2",teamMembers);

From the above dictionary, I need to select the Country1 's first element Country1Player1 and assign to some variable. After that I need to remove that value alone from the value list.

Expected output: If I pass key as 'Country1' then it should give me Country1Player1 and that value needs to be removed the data dictionary. Key Country1 should contain only Country1Player2 & Country1Player3 in the list of values.

CodePudding user response:

string firstTeamMember = null;
if (data.TryGetValue("Country1", out List<string> list) && list?.Any() == true)
{
    firstTeamMember = list[0];
    list.RemoveAt(0);
}

CodePudding user response:

You could try sth like this:

if(data.TryGetValue("Country1", out var values))
{
    var firstValue = values?.FirstOrDefault();
    data["Country1"] = data["Country1"]?.Skip(1).ToList();
}
  • Related