获取基于价值在C#字典中的键/值对指数 [英] Get index of a key/value pair in a C# dictionary based on the value

查看:101
本文介绍了获取基于价值在C#字典中的键/值对指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果某些属性或方法存在获取特定值的索引。

I would like to know if some property or method exists that gets the index of a specific value.

我发现字典有载有()方法如果传入的值存在,所以这种方法几乎实现了什么,我需要返回true。

I found that dictionaries have the Contains() method which returns true if the value passed in exists, so this method almost implements what I need.

我知道我可以通过所有的值对循环并检查车况,但我想问,因为也许有这样的优化方式。

I know that I can loop through all the value pairs and check the condition, but I ask because maybe there's an optimized way of doing this.

推荐答案

有一个字典中的指数没有这样的概念 - 这是从根本上无序的。当然,当你迭代它,你会得到中的项目的部分的命令,但该命令并不能完全保证(特别是如果您添加或删除的条目)可以随时间而改变。

There's no such concept of an "index" within a dictionary - it's fundamentally unordered. Of course when you iterate over it you'll get the items in some order, but that order isn't guaranteed and can change over time (particularly if you add or remove entries).

显然,你可以从 KeyValuePair 只是通过使用键属性,所以,可以让你使用的词典的索引:

Obviously you can get the key from a KeyValuePair just by using the Key property, so that will let you use the indexer of the dictionary:

var pair = ...;
var value = dictionary[pair.Key];
Assert.AreEqual(value, pair.Value);

您还没有真正说你想要做什么。如果你试图找到对应于某个特定值的一些关键,你可以使用:

You haven't really said what you're trying to do. If you're trying to find some key which corresponds to a particular value, you could use:

var key = dictionary.Where(pair => pair.Value == desiredValue)
                    .Select(pair => pair.Key)
                    .FirstOrDefault();



将是无效如果条目没有按T存在。

key will be null if the entry doesn't exist.

这是假设的密钥类型是引用类型...如果它是一个值类型,你需要做的事情略有不同。

This is assuming that the key type is a reference type... if it's a value type you'll need to do things slightly differently.

当然,如果你真的想通过键查找值,你应该考虑使用其他字典它倒过来映射除了现有的字典。

Of course, if you really want to look up values by key, you should consider using another dictionary which maps the other way round in addition to your existing dictionary.

这篇关于获取基于价值在C#字典中的键/值对指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆