Linq Syntax - Selecting multiple columns

后端 未结 3 1654
轮回少年
轮回少年 2020-11-29 21:24

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

IQueryable objEmployee = null;

objEmployee = from res in _db.EMPLOYEEs
                     


        
相关标签:
3条回答
  • 2020-11-29 21:55
     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 { }

    0 讨论(0)
  • 2020-11-29 22:09

    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 };
    
    0 讨论(0)
  • 2020-11-29 22:10

    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);
    
    0 讨论(0)
提交回复
热议问题