在LINQ Lambda表达式中连接两个列的值

14
我有一张表格,其中有两列。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表达式实现这个功能?

1
在SQL中,通常应使用' '表示包含空格的字符串,而不是使用" " - Mark Byers
还可以看一下这个链接:http://pranayamr.blogspot.ca/2010/12/sql-to-linq-visual-representation.html,它可能会帮助你获取更多关于LINQ的信息。 - Pranay Rana
检查我更新的答案,可能会对你有所帮助。 - Pranay Rana
7个回答

25
你可以使用字符串连接:
select new
{
    Username = CurrentUser.First_Name + " " + CurrentUser.Last_Name,
    CurrentUser.Email_ID,
    CurrentUser.GUID
};

4
尝试一下
     select new
            {
                          FullName = CurrentUser.First_Name + " " + CurrentUser.Last_Name,
                          CurrentUser.Email_ID,
                          CurrentUser.GUID
            };

谢谢大家,所有的解决方案都很好用。我希望我能将它们全部标记为正确,但我只能标记一个 :( - Manas Saha

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
                  };

1

你应该给你的匿名类型提供“键”(只读属性):

select new
{
  Name = CurrentUser.First_Name + " " + CurrentUser.Last_Name,
};

然后在分配用户名时,只需将字符串连接起来。


1

看一下 CLR方法到规范函数的映射
.Net提供了许多可以直接映射到查询的方法,您必须使用其中之一来添加两个字符串
所以您可以使用其中的一个

select new 
{ 
    Username = Concat(first_Name,Last_Name), 
    CurrentUser.Email_ID, 
    CurrentUser.GUID 
}; 

1

这是另一种可行的变体,尚未列出:

var allUserList =  objDataContext.Users.Where(c => c.Is_Deleted != false).
     Select(s => new{First_Name + " " + Last_Name, Email_ID, GUID});

2
var allUserList = objDataContext.Users.Where(c => c.Is_Deleted != false).Select(s => new{FullName = First_Name + " " + Last_Name, Email_ID, GUID}); 对我很有用。我需要将FullName作为一个字段添加。 - Charly H

0
select new
{
    Username = string.Format("{0} {1}", CurrentUser.First_Name, CurrentUser.Last_Name),
    CurrentUser.Email_ID,
    CurrentUser.GUID
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接