[英]Split Strings into a Dictionary
I'm trying to join 3 different values in an app.config so they correlate. 我正在尝试在app.config中加入3个不同的值,以便它们相互关联。
<add key="User" value="User1,User2,User3,Pass4" />
<add key="Pass" value="Pass1,Pass2,Pass3,Pass4" />
<add key="Location" value="Location1,Location2,Location3,Location4" />
var User = ConfigurationManager.AppSettings.Get("User").Split(new[] { ',' });
var Pass = ConfigurationManager.AppSettings.Get("Pass").Split(new[] { ',' });
var Location = ConfigurationManager.AppSettings.Get("Location").Split(new[] { ',' });
I'm having no trouble doing a split on the comma to get each value for each key. 我毫不费力地在逗号上进行拆分以获取每个键的每个值。 What I want to do is have User1 go with Pass1 and Location1.
我想要做的是让User1与Pass1和Location1一起使用。 Is this something that I could easily do via a hashtable/dictionary?
通过哈希表/字典,我可以轻松做到这一点吗? If so what's the easiest way?
如果是这样,最简单的方法是什么?
The best way would probably be to define a class to hold them: 最好的方法可能是定义一个类来保存它们:
public class UserInfo
{
public string User { get; private set; }
public string Pass { get; private set; }
public string Location { get; private set; }
public UserInfo(string user, string pass, string location)
{
this.User = user;
this.Pass = pass;
this.Location = location;
}
}
Then a simple loop to build them: 然后是一个简单的循环来构建它们:
List<UserInfo> userInfos = new List<UserInfo>();
for(int i = 0; i < User.Length; i++)
{
var newUser = new UserInfo(User[i], Pass[i], Location[i]);
userInfos.Add(newUser);
}
Then if you did want a lookup table or dictionary based on say, User
: 然后,如果您确实想要基于
User
的查找表或字典:
Dictionary<string, UserInfo> userLookup = userInfos.ToDictionary(userInfo => userInfo.User);
EDIT: You may also want to do a quick check to make sure you have the proper amount of corresponding information as well before you build your objects: 编辑:您可能还想进行快速检查,以确保您在构建对象之前也具有适当数量的相应信息:
if (User.Length != Pass.Length || User.Length != Location.Length)
throw new Exception("Did not enter the same amount of User/Pass/Location data sets!");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.