IEnumerable<string> permissionList;
Dictionary<string, bool> permissions = new Dictionary<string, bool>();
foreach (string item in permissionList)
{
permissions.Add(item, false);
}
推荐一下resharper 代码重构工具
IEnumerable<string> permissionList = null;
Dictionary<string, bool> permissions = permissionList.ToDictionary(item => item, item => false);
大概就是这样了
列表变为字典是需要判断键是否重复,键是否有大小写约束,从程序的角度考虑,你还需要判空,去重。当然如果仅仅是列表变字典,优化的写法很简单,如下:
IEnumerable<string> permissionList = null; Dictionary<string, bool> permissions = null; if (permissionList == null) { permissions = new Dictionary<string, bool>(); return permissions; } permissions = permissionList.Distinct().ToDictionary(x => x, y => { return false; });
应该只能算简写吧。。外加key不唯一也没有判断。