问题描述
UserKey UserName
------------------------
1 John Smith
2 Andrew Wright
3 David Morgan
4 Judy brown
5 ........
在C#中,有人可以告诉我如何编写函数/方法以将用逗号分隔的键字符串转换为也用逗号分隔的用户名字符串。在数据库表用户中定义了UserKey和UserName匹配项。例如,函数/方法应将字符串“ 1,2,3,4"
转换为字符串"John Smith,Andrew Wright,David Morgan,Judy brown"
。
非常感谢您!
解决方法
您可以尝试将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,4";
string result = Regex.Replace(source,"[0-9]+",match =>
cache.TryGetValue(match.Value,out var name) ? name : "???");
,
这是您的方法。我假设您已经有了一种方法,可以从数据库(GetUserFromDb
)中按ID查找用户,所以我只是使用静态数组来模拟该部分。
void Main()
{
var userKeysString = "1,xx,732,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; }
}