2012-04-19 100 views
10

我是新来的LINQ和lambda表达式那些正在出现棘手我:(连接两个列的值

我那里有两列。FIRST_NAME和另外姓氏。我用填充一个gridview表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查询什么,我想acchieve会像这个:

Select First_name + ' ' + Last Name as Username, Email_ID, GUID 
From tbl_Users where Is_Deleted != false 

我该如何通过lambda表达式来实现?

+1

在SQL中,您通常应该使用''''表示包含空格的字符串,而不是'“”'。 – 2012-04-19 09:26:31

+0

哇,如果一切都那么简单 – Habib 2012-04-19 09:27:13

+0

aslo看看:http://pranayamr.blogspot.ca/2010/12/sql-to-linq-visual-representation.html可能会帮助你获得更多关于linq – 2012-04-19 09:47:24

回答

14

您可以使用字符串连接:

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

谢谢大家,所有的解决方案工作正常。我希望我能标记所有这些是正确的,但我只能标记一个:( – 2012-04-19 09:31:28

1

你应该给你的anonymous type '钥匙'(只读属性):

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

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

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

看看这个CLR Method to Canonical Function Mapping
的.Net提供了可以直接映射到查询许多方法ULL不得不使用其中的一个添加两个字符串
这样一个u可以使用的

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

这里还有一个变化,工程和尚未上市:

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

'var allUserList = objDataContext.Users.Where(c => c.Is_Deleted!= false).Select(s => new {FullName = First_Name +“”+ Last_Name,Email_ID,GUID});'为我工作,我需要将FullName作为字段添加 – 2017-04-26 07:03:04