我是LinQ的新手,那些lambdas对我来说显得很棘手:(
我有一个表有两列。 First_Name和Last_name。我正在使用LinQ填充gridview。
protected void Page_Load(object sender, EventArgs e)
{
myLinQtoSQLClassDataContext objDataContext = new myLinQtoSQLClassDataContext();
var allUserList = from CurrentUser in objDataContext.Users.Where(c => c.Is_Deleted != false)
select new
{
CurrentUser.First_Name,
CurrentUser.Last_Name,
CurrentUser.Email_ID,
CurrentUser.GUID
};
GridView1.DataSource = allUserList;
GridView1.DataBind();
}
我可以使用LinQ检索这些值,但我希望将名字和姓氏连接起来,并且中间有一个空格。
我试图改进的等效SQL查询将是这样的:
Select First_name + ' ' + Last Name as Username, Email_ID, GUID
From tbl_Users where Is_Deleted != false
如何通过lambda表达式实现这一目标?
答案 0 :(得分:19)
您可以使用字符串连接:
select new
{
Username = CurrentUser.First_Name + " " + CurrentUser.Last_Name,
CurrentUser.Email_ID,
CurrentUser.GUID
};
答案 1 :(得分:4)
尝试
select new
{
FullName = CurrentUser.First_Name + " " + CurrentUser.Last_Name,
CurrentUser.Email_ID,
CurrentUser.GUID
};
答案 2 :(得分:2)
var allUserList = from CurrentUser in objDataContext.Users.Where(c => c.Is_Deleted != false)
select new
{
Name = CurrentUser.First_Name + " " + CurrentUser.Last_Name,
CurrentUser.Email_ID,
CurrentUser.GUID
};
答案 3 :(得分:1)
您应该提供anonymous type'密钥' (只读属性):
select new
{
Name = CurrentUser.First_Name + " " + CurrentUser.Last_Name,
};
然后在分配用户名时连接字符串。
答案 4 :(得分:1)
看看这个CLR Method to Canonical Function Mapping
.Net提供了许多方法,可以直接映射到查询ull必须使用其中一个添加两个字符串
所以你可以使用的是
select new
{
Username = Concat(first_Name,Last_Name),
CurrentUser.Email_ID,
CurrentUser.GUID
};
答案 5 :(得分:0)
这是另一个有效但尚未列出的变体:
var allUserList = objDataContext.Users.Where(c => c.Is_Deleted != false).
Select(s => new{First_Name + " " + Last_Name, Email_ID, GUID});
答案 6 :(得分:0)
select new
{
Username = string.Format("{0} {1}", CurrentUser.First_Name, CurrentUser.Last_Name),
CurrentUser.Email_ID,
CurrentUser.GUID
};