【发布时间】:2017-07-16 04:16:07
【问题描述】:
我想定义一个结构来帮助我维护这个键值对列表 -
"ABC", "010"
"ABC", "011",
"BAC", "010"
"BAC" , "011"
"CAB", "020"
然后我想写一个方法来传入 ("ABC" , "010" ) 看看这个映射是否存在 & 如果它存在则方法返回 true。
我应该使用什么结构以及方法看起来如何?
我试过了——
public bool IsAllowed(string source, string dest)
{
bool allowed = false;
var allowedDest = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("ABC","010"),
new KeyValuePair<string, string>("ABC","011"),
new KeyValuePair<string, string>("BAC","010"),
new KeyValuePair<string, string>("BAC","011"),
new KeyValuePair<string, string>("CAB","020"),
new KeyValuePair<string, string>("CAB","030")
};
// How to check for mapping?
return allowed;
}
【问题讨论】:
-
这个怎么样:
allowed = allowedDest.Any(c => c.Equals(new KeyValuePair<string, string>("ABC", "010"))); -
感觉就像你只想使用
Dictionary<string, string>。然后用TryGetValue检查给定键的值是否存在;如果返回 true,则映射存在。
标签: c# .net linq c#-4.0 key-value