Linq Syntax - select multiple columns

This is my Linq syntax that I use for 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 to select multiple columns? Like I want to choose res.ID. And how can I get them? I think IQueryable is not working. And this is called Linq to SQL - right?

+69
c # linq entity-framework
Jul 21 '11 at 6:45
source share
3 answers

As the other answers pointed out, you need to use an anonymous type.

Regarding the syntax, I personally prefer the chaining method. The equivalent of a chain of methods 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 chain of method calls similar to this during compilation.

UPDATE

If you need the whole object, you just need to omit the Select() call, i.e.

 var employee = _db.EMPLOYEEs .Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo); 
+135
Jul 21 '11 at 6:52
source share

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 }; 
+62
Jul 21 2018-11-11T00:
source share
  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:

  • Select employee from db as res.

  • Filter employee information in accordance with the terms of the condition.

  • Select the required fields from the employee object by creating an anonymous object using the new {}

+3
Apr 27 '16 at 12:48
source share



All Articles