122

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 ?

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Riz
  • 6,746
  • 16
  • 67
  • 89
  • 3
    LinqToSql and entity framework are different. See http://stackoverflow.com/questions/8676/entity-framework-vs-linq-to-sql – gideon Jul 21 '11 at 06:48

3 Answers3

245

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);
Adam Ralph
  • 29,453
  • 4
  • 60
  • 67
77

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 };
Ivan Danilov
  • 14,287
  • 6
  • 48
  • 66
  • can you suggest how to properly write this expression: select new { (DateTime.Now - debt.ClaimDate), debt.Amount}; ? It throws an error: Invalid anonymous type member declarator – Dainius Kreivys Sep 19 '16 at 13:13
  • 1
    @DainiusKreivys `select new { Diff = (DateTime.Now - debt.ClaimDate), Amount = debt.Amount}`. The form used in the answer is a shorthand, where member name in the initialization expression is used as a field name of anonymous type. E.g. `new {res.EMAIL, res.USER_NAME}` is a shorthand for `new {EMAIL = res.EMAIL, USER_NAME = res.USER_NAME}`. In case there's an expression, as in your case with dates - shorthand does not applicable, hence compiler error. – Ivan Danilov Sep 21 '16 at 14:50
7
 var employee =  (from res in _db.EMPLOYEEs
 where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
 select new {res.EMAIL, res.USERNAME} );

OR you can use

 var employee =  (from res in _db.EMPLOYEEs
 where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
 select new {email=res.EMAIL, username=res.USERNAME} );

Explanation :

  1. Select employee from the db as res.

  2. Filter the employee details as per the where condition.

  3. Select required fields from the employee object by creating an Anonymous object using new { }

Bimzee
  • 1,138
  • 12
  • 15