簡體   English   中英

在這種情況下如何檢查鍵值對映射?

[英]How to check for key-value pair mapping in this scenario?

我想定義一個結構來幫助我維護此鍵值對列表-

"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方法從列表中檢索具有匹配源和目標的項目。

如果找到項目,則將其返回,否則將返回KeyValuePair的默認值。 然后,您需要檢查它是否返回默認值,並根據該值返回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;
    }

這應該可以幫助您解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM