我陷入了一种情况,我试图为给定的用户名生成密码.
我正在通过文本框为FirstName和LastName创建用户输入的用户名,用户的姓氏+名字的第一个字母.例如,如果用户的名字是'Ronald'而且姓氏是'Test',我将数据库中的用户名添加为'Testr'.但是,如果我为另一个用户使用相同的姓氏,并且名字以与数据库中现有用户相同的名称开头,我会添加名字的前2个字母,如下所示 -
if (entities.Users.Any(a => a.LastName == tbLname.Text && a.FirstName.StartsWith(fname)))
username = (tbLname.Text + tbFname.Text.Substring(0,2)).ToLower();
Run Code Online (Sandbox Code Playgroud)
现在的问题是,只有当前两个字母与第一个名字匹配时才有效.如果我有3个甚至4个匹配名字怎么办?我不知道如何检查剩余的字符是否具有唯一的用户名.
有关如何实现这一点的任何想法?提前致谢.
如果应用程序想要避免错误,OP需要更多信息,但同时这应该解决手头的问题.
//Store the first possible name.
var possibleUsername = string.Format("{0}{1}", tbLname.Text, tbFname.Text.Substring(0,1))
//Don't hit the database N times, instead get all the possible names in one shot.
var existingUsers = entities.Users.Where(u => u.Username.StartsWith(possibleUsername)).ToList();
//Find the first possible open username.
if (existingUsers.Count == 0) {
//Create the user since the username is open.
} else {
//Iterate through all the possible usernames and create it when a spot is open.
for(var i = 1; i < existingUsers.Count; i++) {
if (existingUsers.FirstOrDefault(u => u.Username == string.Format("{0}{1}", tbLname.Text, tbFname.Text.Substring(0, i))) == null) {
//Create the user since the user name is open.
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2497 次 |
| 最近记录: |