0

enter image description here

public static Dictionary<string, User> userList = new Dictionary<string, User>();

That's how "userList" gets declared in another class. BTW the name of that class is "User" the same as the type, which could cause the problem but i am not sure. I have no idea how to make this work honestly.

Here's the full script: https://pastebin.com/h56ukpgR Some things in the script dont make sense yet because i copied some stuff from another script.

But basically i am trying to check if a nickName already exists in a static dictionary, and if so notify the user and don't do anything else.

  • What are the keys in the dictionary? If they're the nicknames you can lookup the key. Otherwise you can iterate all users with `foreach(User u in User.userList.Values)`. – Lee Jan 07 '20 at 12:04

2 Answers2

6

User.userList is a Dictionary<string, User>. If you iterate over it, each element is a KeyValuePair<string, User>, not a User.

So you can either do:

foreach (KeyValuePair<string, User> kvp in User.userList)
{
    User user = kvp.Value;
} 

Or you can iterate directly over the dictionary's values:

foreach (User user in user.userList.Values)
{
}

If the key for each User in your dictionary is the user's nickname, then you don't need the loop at all. Your code:

foreach (User u in User.userList)
{
    string uN = u.GetNickName();
    if (name == uN)
    {
        builder.WithTitle("A practice with the name you specified already exists!");
        goto EndFunction;
    }
}

EndFunction:
await ReplyAsync("", false, builder.Build());

Can be replaced with:

if (User.userList.ContainsKey(name))
{
    builder.WithTitle("A practice with the name you specified already exists!");
}

await ReplyAsync("", false, builder.Build());

If not, you can still simplify this code using linq's Any:

if (User.userList.Values.Any(x => x.GetNickName() == name))
{
    builder.WithTitle("A practice with the name you specified already exists!");
}

await ReplyAsync("", false, builder.Build());

Finally, using goto in this way is not recommended. You can break out of a loop simply by using break;.

preciousbetine
  • 2,959
  • 3
  • 13
  • 29
canton7
  • 37,633
  • 3
  • 64
  • 77
2

For future readers, an hint to solving these kinda problems is to look at the error message. Here it says:

Cannot convert KeyValuePair<string, User> to User

That simply means the expected cast is a KeyValuePair<string, User> and not a User.

So, your code would work if you replace User In the loop with KeyValuePair<string, User>.

canton7
  • 37,633
  • 3
  • 64
  • 77
preciousbetine
  • 2,959
  • 3
  • 13
  • 29