寻找一种将分隔字符串转换为StringDictionary的更简便的方法
本文关键字:StringDictionary 方法 转换 字符串 一种 分隔 寻找 | 更新日期: 2023-09-27 18:10:55
我创建了以下代码,将一些数据公开为正则表达式匹配字符串和StringDictionary。感觉我可以用更少的行使用LINQ来完成这个任务。
private const string STREETTYPES = @"ALY|Alley|AVE|Avenue|BLVD|Boulevard|CIR|Circle|CT|Court|CTR|Center|DR|Drive|EXPY|Expressway|FWY|Freeway|HALL|Hall|HWY|Highway|JCT|Junction|LN|Lane|LP|Loop|PIKE|Pike|PKWY|Parkway|PL|Place|RD|Road|ST|Street|TER|Terrace|TPKE|Turnpike|TRL|Trail|WAY|Way";
private static StringDictionary streetTypes = null;
public static StringDictionary StreetTypes
{
get
{
if (streetTypes != null) return streetTypes;
streetTypes = new StringDictionary();
var streetArray = STREETTYPES.Split(PIPE);
for (int i = 0; i < streetArray.Length-1; i = i+2)
{
streetTypes.Add(streetArray[i], streetArray[i + 1]);
}
return streetTypes;
}
}
private static readonly StringDictionary streetTypes = new StringDictionary
{
{"ALY","Alley"},{"AVE","Avenue"},{"ALY","Alley"},{"BLVD","Boulevard"},{"CIR","Circle"},
{"CT","Court"},{"CTR","Center"},{"DR","Drive"},{"EXPY","Expressway"},{"FWY","Freeway"},
{"HALL","Hall"},{"HWY","Highway"},{"JCT","Junction"},{"LN","Lane"},{"LP","Loop"},
...
};
如果需要重新计算,可以使用Linq,但如果字典是静态的,则只需使用初始化式:
var input = STREETTYPES.Split('|');
var dict = input.Select( (x,i) => new { Item = x, Index = i })
.Where(x => x.Index % 2 == 0)
.ToDictionary( x=> input[x.Index], x => input[x.Index + 1]);
这有什么好处吗?
var x = STREETTYPES.Split(new[] {'|'});
var output = Enumerable
.Range(0, x.Length / 2)
.ToDictionary(s => x[2 * s], s => x[2 * s + 1]);
也许可以再压紧一点,但我今晚半睡半醒。
这将为您提供您所寻找的StringDictionary
,而无需进行位置数学。如果你可以使用Dictionary
,我会使用它和其他发布的解决方案之一。
var types = new StringDictionary();
using (IEnumerator<string> enumerator = streetTypes.Split('|').AsEnumerable().GetEnumerator())
{
while(enumerator.MoveNext())
{
string first = enumerator.Current;
if (!enumerator.MoveNext())
break;
types.Add(first, enumerator.Current);
}
}
无耻地剽窃Python字典构造函数:
IDictionary<TKey, TVal>
ToDictionary<TKey, TVal>(IEnumerable<TKey> keys,
IEnumerable<TVal> values)
{
return keys.Zip(values, (k, v)=>new {K=k, V=v}).ToDictionary(kv=>kv.K, kv=>kv.V);
}
var str = @"ALY|Alley|AVE|Avenue|BLVD|Boulevard|CIR|Circle|CT|Court|CTR|Center|DR|Drive|EXPY|Expressway|FWY|Freeway|HALL|Hall|HWY|Highway|JCT|Junction|LN|Lane|LP|Loop|PIKE|Pike|PKWY|Parkway|PL|Place|RD|Road|ST|Street|TER|Terrace|TPKE|Turnpike|TRL|Trail|WAY|Way";
var words = str.Split('|');
var keys = words.Where((w, i) => i%2 == 0);
var values = words.Where((w, i) => i%2 != 0);
var dict = ToDictionary(keys, values);
这将产生Dictionary<string, string>
,而不是StringDictionary
。后者没有任何复制构造函数,因此不能使用联机器创建。
(现在我希望c#对特别数据结构的基本支持少一些,我想念解构赋值。)
不需要Zip()的替代版本,因此可以在旧版本的。net上工作,并避免分配临时键/值对列表:
IDictionary<TKey, TVal>
ToDictionary<TKey, TVal>(IEnumerable<TKey> keys,
IEnumerable<TVal> values)
{
return Enumerable.Range(0, keys.Count()).ToDictionary(i=>keys.ElementAt(i), i=>values.ElementAt(i));
}