0

目前在我的 ASP.Net 应用程序 web.config 中,我有一个应用程序设置,它存储一个以逗号分隔的映射值列表,如下所示。在后面的代码中,我需要根据输入值 1、2、3 等对此数据执行查找。我可以将字符串拆分并循环,直到找到匹配项,或者使用正则表达式从配置字符串中提取值。

目前我正在使用正则表达式来获取映射值。我不反对更改数据在 web.config 中的存储方式。有没有更简单优雅的处理方式?

<add key="Mappings" value="1|APP,2|TRG,3|KPK,4|KWT,5|CUT" />
4

3 回答 3

1

只是好奇:) LINQ 怎么样

string inputValue = "2";
string fromConfig = "1|APP,2|TRG,3|KPK,4|KWT,5|CUT";            
string result = fromConfig
    .Split(',')
    .Where(s => s.StartsWith(inputValue))
    .Select(s => s.Split('|')[1])
    .FirstOrDefault();

或者

Regex parseRegex = new Regex(@"((?<Key>\d)\|(?<Value>\S{3}),?)");
parseRegex.Matches(fromConfig)
    .Cast<Match>()
    .Where(m => m.Groups["Key"].Value == inputValue)
    .Select(m => m.Groups["Value"].Value)
    .FirstOrDefault();
于 2009-02-13T00:24:51.157 回答
1

如果您需要经常使用此查找并且 web.config 中的字符串不会经常更改,那么将字符串解析为 Dictionary 对象并将其存储在应用程序或缓存中是有意义的。

从字典中查找将是闪电般的速度,尤其是与每次解析字符串相比。

private static readonly object _MappingsLock = new object();

public static string GetMapping(int id)
{
    // lock to avoid race conditions
    lock (_MappingsLock)
    {
        // try to get the dictionary from the application object
        Dictionary<int, string> mappingsDictionary =
            (Dictionary<int, string>)Application["MappingsDictionary"];

        if (mappingsDictionary == null)
        {
            // the dictionary wasn't found in the application object
            // so we'll create it from the string in web.config
            mappingsDictionary = new Dictionary<int, string>();

            foreach (string s in mappingsStringFromWebConfig.Split(','))
            {
                string[] a = s.Split('|');
                mappingsDictionary.Add(int.Parse(a[0]), a[1]);
            }

            // store the dictionary in the application object
            // next time around we won't need to recreate it
            Application["MappingsDictionary"] = mappingsDictionary;
        }

        // now do the lookup in the dictionary
        return mappingsDictionary[id];
    }
}

// eg, get the mapping for id 4
string mapping = GetMapping(4);  // returns "KWT"
于 2009-02-13T00:51:49.923 回答
0

用逗号分割字符串,然后用 | 分割每个子字符串,将它们存储在字典中并按键查找。

这只是作为 Regex 的替代品。你知道他们对 Regex 的评价。

于 2009-02-13T00:03:02.207 回答