如何在此方案中检查键值对映射



我想定义一个结构来帮助我维护这个键值对列表 -

"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;
}

如果它是一个大列表,我会声明

HashSet<Tuple<string,string>> Allowed = new HashSet<Tuple<string,string>>();
Allowed.Add(Tuple.Create<string,string>("ABC","010");
[... and all the others]
if (Allowed.Contains(Tuple.Create<string,string>("ABC","010")) { }

如果它是一个小列表,您可以使用 foreach 语句或 .Any() 命令。

你可以保持简单,并使用字符串数组数组。

public bool IsAllowed(string source, string dest)
{
var allowedDest = new []
{
new [] {"ABC", "010"},
new [] {"ABC", "011"},
new [] {"BAC", "010"}
//...
};
var match = new [] { source, dest };
return allowedDest.Any(x => x.SequenceEqual(match));
}

您需要在此处使用 Linq 方法。

可以使用 FirstOrDefault 方法通过比较列表中项的键和值,从具有匹配源和目标的列表中检索项。

如果找到项目,将返回,否则将返回键值对的默认值。 然后,您需要检查它是否返回默认值,并在此基础上返回true或false。

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")
};
var item = allowedDest.FirstOrDefault(kvpair => kvpair.Key == source && kvpair.Value == dest);
allowed = !item.Equals(default(KeyValuePair<string, string>));
return allowed;
}

这应该可以帮助您解决问题。

最新更新