【问题标题】:In C#, how I can convert a comma separated key string to an actual value string? [closed]在 C# 中,如何将逗号分隔的键字符串转换为实际值字符串? [关闭]
【发布时间】:2020-08-24 21:03:17
【问题描述】:

有一个名为 user 的数据库表,假设它具有以下结构和值:

UserKey    UserName
------------------------
1          John Smith
2          Andrew Wright
3          David Morgan
4          Judy Brown
5          ........

在 C# 中,谁能告诉我如何编写一个函数/方法来将用逗号分隔的键字符串转换为用户名字符串,也用逗号分隔。 UserKey 和 UserName 匹配在数据库表 user 中定义。例如,函数/方法应将字符串“1,2,3,4"”转换为字符串"John Smith,Andrew Wright,David Morgan,Judy Brown"

非常感谢!

【问题讨论】:

  • 您能否将 RDBMS 表缓存到 C# 集合中,例如 Dictionary<string, string>
  • 我不确定,您是在问我是否有权限或想这样做吗?我不确定,但我肯定想试试。

标签: c# string data-conversion


【解决方案1】:

您可以尝试将 Rdbms 表缓存C# 集合中,例如,Dictionary<string, string>:

  Dictionary<string, string> cache = new Dictionary<string, string>();

  //TODO: I've assumed that RDBMS is MS SQL Server; put the right types here
  using (var conn = new SqlConnection(connectionStringHere)) {
    conn.Open();

    string sql =
      @"select [UserKey],
               [UserName]
          from [User]";

    using (var q = new SqlCommand(sql, conn)) {
      using (var reader = q.ExecuteReader()) {
        while (reader.Read()) {
          cache.Add(Convert.ToString(reader[0]), Convert.ToString(reader[1]));
        }
      }
    }
  }

然后你可以在 Linq 的帮助下查询cache

  string source = "1,2,3,4";

  string result = string.Join(",", source
    .Split(',')
    .Select(key => cache.TryGetValue(key.Trim(), out var name) ? name : "???"));

或者通过正则表达式:

  string source = "1,2,3,4";

  string result = Regex.Replace(source, "[0-9]+", match =>
    cache.TryGetValue(match.Value, out var name) ? name : "???");

【讨论】:

  • 非常感谢德米特里的帮助。我明天试试,然后告诉你。
【解决方案2】:

您可以这样做。我假设您已经找到了一种通过 id 从您的数据库 (GetUserFromDb) 中查找用户的方法,所以我只是使用静态数组模仿了该部分。

void Main()
{
    var userKeysString = "1,2,,xx,732,3,4";
    var userNamesString = GetUserNames(userKeysString); 
}

public string GetUserNames(string userKeys)
{
    var keys = userKeys.Split(",").Select(x => int.TryParse(x, out var i) ? i : 0);
    return string.Join(", ", keys.Where(k => k > 0).Select(k => GetUserFromDb(k)?.UserName).Where(u => u != null));
}

private User GetUserFromDb(int userKey)
{
    return AllDbUsers.FirstOrDefault(u => u.UserKey == userKey);
}

public static User[] AllDbUsers = new User[]
{
    new User { UserKey = 1, UserName = "John Smith"},
    new User { UserKey = 2, UserName = "Andrew Wright"},
    new User { UserKey = 3, UserName = "David Morgan"},
    new User { UserKey = 4, UserName = "Judy Brown"},
    new User { UserKey = 5, UserName = "John Doe"},
};

public class User
{
    public int UserKey { get; set; }
    public string UserName { get; set; }
}

【讨论】:

  • 非常感谢 Hiral 的帮助。我明天试试,然后告诉你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
  • 2019-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
相关资源
最近更新 更多