Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Syntax - Selecting multiple columns

This is my Linq Syntax which I am using to my entity model

IQueryable<string> objEmployee = null;  objEmployee = from res in _db.EMPLOYEEs               where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)               select res.EMAIL; 

How can I select multiple columns? Like I want to select res.ID aswell. And how can I receive those? IQueryable will not work I think. And this is called Linq to SQL - right ?

like image 644
Riz Avatar asked Jul 21 '11 06:07

Riz


People also ask

How do you use select many?

SelectMany(<selector>) method For example, SelectMany() can turn a two-dimensional array into a single sequence of values, as shown in this example: int[][] arrays = { new[] {1, 2, 3}, new[] {4}, new[] {5, 6, 7, 8}, new[] {12, 14} }; // Will return { 1, 2, 3, 4, 5, 6, 7, 8, 12, 14 } IEnumerable<int> result = arrays.


2 Answers

As the other answers have indicated, you need to use an anonymous type.

As far as syntax is concerned, I personally far prefer method chaining. The method chaining equivalent would be:-

var employee = _db.EMPLOYEEs     .Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo)     .Select(x => new { x.EMAIL, x.ID }); 

AFAIK, the declarative LINQ syntax is converted to a method call chain similar to this when it is compiled.

UPDATE

If you want the entire object, then you just have to omit the call to Select(), i.e.

var employee = _db.EMPLOYEEs     .Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo); 
like image 126
Adam Ralph Avatar answered Sep 21 '22 18:09

Adam Ralph


You can use anonymous types for example:

  var empData = from res in _db.EMPLOYEEs                 where res.EMAIL == givenInfo || res.USER_NAME == givenInfo                 select new { res.EMAIL, res.USER_NAME }; 
like image 25
Ivan Danilov Avatar answered Sep 19 '22 18:09

Ivan Danilov