将字符串拆分为字典

时间:2013-04-26 01:58:11

标签: c# .net

我正在尝试在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[] { ',' });

我可以毫不费力地对逗号进行拆分以获取每个键的每个值。我想要做的是让User1使用Pass1和Location1。这是我可以通过哈希表/字典轻松完成的吗?如果是这样,最简单的方法是什么?

1 个答案:

答案 0 :(得分:8)

最好的方法可能是定义一个类来保存它们:

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;
    }
}

然后用一个简单的循环来构建它们:

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

然后,如果 想要查找表或字典,请基于User

Dictionary<string, UserInfo> userLookup = userInfos.ToDictionary(userInfo => userInfo.User);

编辑:在构建对象之前,您可能还需要进行快速检查以确保您拥有适当数量的相应信息:

if (User.Length != Pass.Length || User.Length != Location.Length)
    throw new Exception("Did not enter the same amount of User/Pass/Location data sets!");