我正在寻找正确的集合,以用于以下情况:
每个露营都是独一无二的,每个孩子都是独一无二的,但不一定要在露营中。在代码中,我会将其构建为:
Dictionary<Camping, List<Child>> list = new Dictionary<Camping, List<Child>>()然后对于每个在露营的孩子
private void AddChildToCamping(Camping camping, Child child)
{
if (!list .ContainsKey(camping))
{
list .Add(camping, new List<string>());
}
list[camping].Add(child);
}但稍后我们需要快速查看孩子是否在野营中,如果是的话,那么孩子在什么野营中。使用上面的代码,这将意味着循环遍历完整的露营列表和儿童列表。
bool foundInCamping = false;
foreach (Camping key in list.Keys)
{
List<Child> children;
bool ok = list.TryGetValue(key, out children);
if (ok)
{
if (children.Contains(targetChild))
{
foundInCamping = true;
break;
}
}
}有没有更好的方法来实现这一点?
发布于 2013-02-08 18:46:52
唯一的解决方案是有第二个从Child到Camping的字典映射:Dictionary<Child, Camping>
发布于 2013-02-08 18:51:39
为此,我使用了以下扩展方法:
public static KeyType[] ReverseLookup<KeyType, ValueType>(this Dictionary<KeyType, ValueType> subject, object lookupValue)
// where KeyType : class
where ValueType : class
{
var channels =
from KeyValuePair<KeyType, ValueType> dcPair in subject
where dcPair.Value == lookupValue
select dcPair.Key;
return channels.ToArray();
}请注意,尽管每个键只能出现一次,但无法阻止一个值具有多个键,因此将返回ketype[]。
用法: Keytype[] myKeys[] = myDictionary.ReverseLookup(myValue);
如果你想要一个一对一的映射字典,我想你必须写你自己的版本……
https://stackoverflow.com/questions/14770769
复制相似问题