如何以首字母大写格式从数据库表中检索值?
我的LINQ查询是这样的,
DBEntities Context = new DBEntities ();
var UserNameEntity = (from a in Context.UserInformation
where a.UserId == UserId
select a).First();
string UserName = UserNameEntity.FirstName + " " + UserNameEntity.LastName;
return UserName;
我收到用户名:bhargav soni
但我希望这应该像Bhargav Soni
我该怎么做?
答案 0 :(得分:2)
这个问题与LINQ无关,但你可以这样做的方法是
TextInfo myTI = CultureInfo.CurrentCulture.TextInfo;
DBEntities Context = new DBEntities ();
var UserNameEntity = (from a in Context.UserInformation
where a.UserId == UserId
select a).First();
string UserName = string.Format("{0} {1}", myTI.ToTitleCase(UserNameEntity.FirstName), myTI.ToTitleCase(UserNameEntity.LastName));
return UserName;
答案 1 :(得分:1)
在FirstName
和LastName
属性上,使用索引器检索第一个字符,然后调用Substring()
方法检索字符串的其余部分。
DBEntities Context = new DBEntities ();
var UserNameEntity = (from a in Context.UserInformation
where a.UserId == UserId
select a).First();
string UserName = char.ToUpper(UserNameEntity.FirstName[0])
+ UserNameEntity.FirstName.Substring(1)
+ " "
+ char.ToUpper(UserNameEntity.LastName[0])
+ UserNameEntity.LastName.Substring(1);
return UserName;
这假设两个属性的长度至少为两个字符。
您也可以完全在LINQ中执行此操作:
DBEntities Context = new DBEntities ();
IEnumerable<string> userNames = from a in Context.UserInformation
where a.UserId == UserId
let firstName = a.FirstName
let lastName = a.LastName
select (char.ToUpper(firstName[0])
+ firstName.Substring(1)
+ " "
+ char.ToUpper(lastName[0])
+ lastName.Substring(1));
return displayNames.First();
显然,使用String.Format代替连接可能会也可能不会提高可读性。
答案 2 :(得分:1)
String
类不包含将字符串转换为标题大小写的方法。 ToTitleCase
方法驻留在TextInfo类中,该类是System.Globalization
命名空间的成员。与String类的ToUpper
和ToLower
方法不同,ToTitleCase
方法不是静态方法,需要类的实例。
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
DBEntities Context = new DBEntities ();
var UserNameEntity = (from a in Context.UserInformation
where a.UserId == UserId
select a).First();
string UserName = textInfo.ToTitleCase(UserNameEntity.FirstName) + " " +
textInfo.ToTitleCase(UserNameEntity.LastName);
return UserName;
检查以获取详细信息: How to convert strings to lower, upper, or title (proper) case by using Visual C#