Home > Net >  How to check and remove if a string variable is in a Dictionary<string, string>?
How to check and remove if a string variable is in a Dictionary<string, string>?

Time:04-12

(Hello I'm a newbie so I have no idea how to do this or even if it was already asked before. And also sorry for my English)

Context: I develop a c# program on the console where the user will write a x,y positions and the algorithm have to count if the user walk through coins (after different movement indications that will influence x and y).

Therefore I created x and y int variables that when put together is a string variable. (Example : "0,2"). Now I need to check if this x,y position is in one of the values in my Dictionary<string, string > and if true, it have to be removed from this Dictionary. (Example of my Dictionary : "coin1", "1,2")

How do I do that ? (Is it clear or do I need to explain more ?)

Here's what I tried but with no sucess :

string coord = x   ","   y;

if (CoinPos.Any(kvp=>kvp.Value.Contains(coord)) == true)
{   
      var result = CoinPos.Where(p => p.Value.Contains(location)).Select(p => p.Key);
                    
       CoinPos.Remove(p.key);
       coinCollected  ;
}

CodePudding user response:

Concatenating the coordinates to a string may not be the best solution because you need to serialize everytime to search, insert, etc and lose some primitive functionality. Maybe you just need a list of tuples of 2 ints to represent the points. But to answer your question:

If this coord can be in more than one item of the dictionary, then

foreach(var item in CoinPos.Where(kvp => kvp.Value == coord).ToList())
{
    CoinPos.Remove(item.Key);
}

Or if there is at best 1 item that can have this value, then

var item = CoinPos.FirstOrDefault(kvp => kvp.Value == coord);

if (item != null) {
    CoinPos.Remove(item.Key);
}

CodePudding user response:

It would be beneficial in this situation to have the point represent the key, and the value be the coin name:

int x = 1;
int y = 2;
Dictionary<string, string> dict = new Dictionary<string, string>();
string point = x   ","   y;
dict.Add(point,"coin1");
if (dict.ContainsKey(point))
{
    dict.Remove(point);
}

Also, for scalability sake, you should create a class called coin, that has some variables like position, and score to obtain. This way you can create and keep track of coins easier. If you did this, you could simply create a list of coin objects and iterate of them checking for their position versus player position. Then you could use the methods "ContainsKey", and "Remove"

CodePudding user response:

OK

string key;
foreach(var kv in CoinPos){
    if(kv.Value == coords){
       key = kv.Key;
       break;
    }
}
if(key.Length > 0)
   CoinPos.Remove(key);

Note.

I would store the co-ordiantes in a Point struct https://docs.microsoft.com/en-us/dotnet/api/system.drawing.point?view=net-6.0

  •  Tags:  
  • c#
  • Related