Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 以x:y>;形式的最佳优雅方式拆分字符串;z得到z_C# - Fatal编程技术网

C# 以x:y>;形式的最佳优雅方式拆分字符串;z得到z

C# 以x:y>;形式的最佳优雅方式拆分字符串;z得到z,c#,C#,我有一些价值观 "name1:password1=>role1,name2:password2=>role2,name3:password3=>role3" 问题是,我需要检查名称和密码是否正确匹配(这些值将在运行时传递)。如果匹配,那么我需要接手这个角色 我当前的实现是 public string IsAuthenticUser(string userId, string password) { var IsauthenticUsers = Syst

我有一些价值观

"name1:password1=>role1,name2:password2=>role2,name3:password3=>role3"
问题是,我需要检查名称和密码是否正确匹配(这些值将在运行时传递)。如果匹配,那么我需要接手这个角色

我当前的实现是

public string IsAuthenticUser(string userId, string password)
    {
        var IsauthenticUsers = System.Configuration.ConfigurationManager.AppSettings["authenticUsers"]
            .Split(',')
            .ToList()
            .Exists(a => a == userId + ":" + password);

       // some other splitting code ...etc....

    }
我可以通过('=>')再次拆分,并可以通过某种方式完成


有没有什么优雅的方法(我相信会有..可能是使用RegEX)来实现这一点?

如果用逗号填充设置,则需要搜索的字符串总是
”,user:password=>“
。我相信有一个正则表达式大师可以给出一行答案,但这也应该可以(假设用户名、密码和角色中没有特殊字符):


如果您对获取信息的
Regex
方法感兴趣,可以尝试以下方法:

string data = "name1:password1=>role1,name2:password2=>role2,name3:password3=>role3";
Match match = Regex.Match(data, "(?<un>\\w+):(?<pw>\\w+)=>(?<role>\\w+)");
while (match.Success)
{
    Console.WriteLine(String.Format("{0} {1} {2}", match.Groups["un"], match.Groups["pw"], match.Groups["role"]));
    match = match.NextMatch();
}

提前解析字符串将在运行时为您节省大量工作

您可以创建一个
字典
,其中元组是(用户名、密码)对,它映射到的字符串是角色

您可以按如下方式进行预处理:

private static KeyValuePair<Tuple<string,string>,string> ParseRole(string s) {
    int pos1 = s.IndexOf(':');
    int pos2 = s.IndexOf("=>", pos1+1);
    if (pos1 < 0 || pos2 < 0) {
        throw new ArgumentException();
    }
    return new KeyValuePair<Tuple<string,string>,string>(
        Tuple.Create(
            s.Substring(0, pos1)
        ,   s.Substring(pos1+1, pos2-pos1-1)
        )
    ,   s.Substring(pos2+2)
    );
}
...
Dictionary<Tuple<string,string>,string> userRoles = BigString
    .Split(',')
    .Select(s=>ParseRole(s))
    .ToDictionary(p => p.Key, p => p.Value);

正如您已经考虑过的那样,我将在
=>
上拆分。您可以使用以下查询:

public string IsAuthenticUser(string userId, string password)
{
    return System.Configuration.ConfigurationManager.AppSettings["authenticUsers"]
        .Split(',')
        .Select(token => token.Split(new[]{"=>"},StringSplitOptions.None))
        .Select(arr => new {  
            Username = arr[0].Split(':')[0], 
            Password = arr[0].Split(':').Last(), 
            Role     = arr.Last()
        })
        .Where(x => x.Username == userId && x.Password == password)
        .Select(x => x.Role)
        .DefaultIfEmpty(null)
        .First();
}

假设字符串的大小不足以导致性能问题,并且您不介意重复多次相同拆分的效率低下,那么为了可读性,我会这样做:

public string IsAuthenticUser(string userId, string password)
{
    var AuthenticUsers = System.Configuration.ConfigurationManager.AppSettings["authenticUsers"];


    return AuthenticUsers 
        .Split(',')
        .Select(user=> new
        {
            login = user.Split(':').First(),
            password = user.Split(':').Last().Split('=').First(),
            role = user.Split(':').Last().Split('>').Last(),
        })
        .Any(user=>user.login == userId && user.password == password);
}
公共字符串IsAuthenticUser(字符串用户ID、字符串密码)
{
字符串userPass=string.Format(“{0}:{1}”,用户ID,密码);
string[]tokens=System.Configuration.ConfigurationManager.AppSettings[“authenticUsers”]
.Split(新字符串[]{“,”,“=>”},StringSplitOptions.RemoveEmptyEntries);
for(int i=0;i
密码存储在一个盒子里,对安全性的影响只是表面上的(通常是微弱的破坏)。存储密码散列确实显著提高了安全性,但如果您使用的是第三方软件,则并不总是一种选择。
string role;
if (!userRoles.TryGetValue(Tuple.Creare(userName, Password), out role)) {
    Console.WriteLine("Role not found");
    return null;
}
return role;
public string IsAuthenticUser(string userId, string password)
{
    return System.Configuration.ConfigurationManager.AppSettings["authenticUsers"]
        .Split(',')
        .Select(token => token.Split(new[]{"=>"},StringSplitOptions.None))
        .Select(arr => new {  
            Username = arr[0].Split(':')[0], 
            Password = arr[0].Split(':').Last(), 
            Role     = arr.Last()
        })
        .Where(x => x.Username == userId && x.Password == password)
        .Select(x => x.Role)
        .DefaultIfEmpty(null)
        .First();
}
public string IsAuthenticUser(string userId, string password)
{
    var AuthenticUsers = System.Configuration.ConfigurationManager.AppSettings["authenticUsers"];


    return AuthenticUsers 
        .Split(',')
        .Select(user=> new
        {
            login = user.Split(':').First(),
            password = user.Split(':').Last().Split('=').First(),
            role = user.Split(':').Last().Split('>').Last(),
        })
        .Any(user=>user.login == userId && user.password == password);
}
public string IsAuthenticUser(string userId, string password)
{
    string userPass = string.Format("{0}:{1}", userId, password);
    string[] tokens = System.Configuration.ConfigurationManager.AppSettings["authenticUsers"]
                            .Split(new string[] {",", "=>"}, StringSplitOptions.RemoveEmptyEntries);
    for (int i = 0; i < tokens.Length; i += 2)
    {
        if (tokens[i] == userPass)
        {
            return tokens[i + 1];
        }
    }
    return null; // no match.
}