2009-02-12 50 views
0

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

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

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

回答

1

如果你需要经常使用此查找和web.config中的字符串不经常改变的话,那将字符串解析成Dictionary对象并将其存储在Application或Cache中是有意义的。

字典中的查找将闪电般快速,特别是与每次解析字符串相比。

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" 
0

拆分上逗号的字符串,然后每串上|,这些存储在一个字典,通过键找到它。

这只是正则表达式的替代方案。你知道他们对Regex的评价。

+0

不,实际上我不知道他们对Regex的评价。为此使用它不是一个好主意吗?我认为Regex是最好的解决方案,因为不需要初始化数组。 – James 2009-02-13 00:09:03

+0

这真是一个笑话。我在这里看到的引用是“当你使用正则表达式解决问题时,现在你有两个问题。”正则表达式版本可能是一个更优雅的解决方案,但如果速度是一个问题,您可以缓存web.config字符串以及字典。 – Moose 2009-02-13 00:23:37

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();