get key of item from dictionary based on value c#

Hi, I’m trying to get from Dictionary one of values as string but I don’t know how :frowning:

public class Items
{
	public string name;
	public Vector3 position;
// and some more variables

	// Instantiate
	public Items(string _name, Vector3 _position)
	{
		this.name = _name;
		this.position = _position;
	}
}

// and later in the same script

public class allBubblesGrid : MonoBehaviour {

public Dictionary<string, Items> inventory = new Dictionary<string, Items>();

public void ModifyItem(Vector3 newPosition)
{
 // here I want to get name (key) from dictionary based on its position

// As far i can get bool which says that item exist:
if(inventory.Any(tr => tr.Value.position.Equals(newPosition)))
			Debug.Log("Exist");

// but I want something like this:
string nameCopy = /* get name of item based on position */ ### cannot get this ###
Items modifiedItem = new Items(nameCopy, newPosition);
inventory[nameCopy] = modifiedItem;
}
}

You can use Linq to select all of the items where there is a certain value:

var keys = dict.Where(item => item.Value.position.Equals(newPosition))
               .Select(item => item.Key);

Its important to note that this is not very efficient with a complexity of O(N) since it has to go through every single item to find all of the items that have the value you’re looking for. Dictionary’s are intended for fast lookup via a key rather than a value so this method should be used sparingly.

TL;DR if you’re doing this not too often, then you should be fine. Since this is inventory related, you probably wont be calling this every frame, so this method should work.