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

z5btuh9x  于 2023-10-13  发布在  其他
关注(0)|答案(7)|浏览(143)

我有一个表,其中有两列。First_Name和Last_Name。我正在使用LINQ填充网格视图。

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表达式实现这一点?

vddsk6oq

vddsk6oq1#

您可以使用字符串连接:

select new
{
    Username = CurrentUser.First_Name + " " + CurrentUser.Last_Name,
    CurrentUser.Email_ID,
    CurrentUser.GUID
};
ui7jx7zq

ui7jx7zq2#

尝试

select new
{
    FullName = CurrentUser.First_Name + " " + CurrentUser.Last_Name,
    CurrentUser.Email_ID,
    CurrentUser.GUID
};
xe55xuns

xe55xuns3#

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

u5i3ibmn4#

您应该给予您的anonymous type“密钥”(只读属性):

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

然后在分配用户名时连接字符串。

nkhmeac6

nkhmeac65#

看看这个CLR Method to Canonical Function Mapping
.Net提供了许多方法,可以直接Map到查询,ul必须使用其中之一来添加两个字符串
所以你可以使用一个是

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

g2ieeal76#

下面是另一种可行的变体,但尚未列出:

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

7gcisfzg7#

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

相关问题