Linq 语法-选择多列

这是我的 Linq 语法,我用它来实现我的实体模型

IQueryable<string> objEmployee = null;


objEmployee = from res in _db.EMPLOYEEs
where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
select res.EMAIL;

如何选择多列?就像我想选择 res.ID 一样。我怎么才能得到这些呢?我认为我可以质疑是行不通的。 这个叫做 Linq to SQL,对吧?

298365 次浏览

您可以使用匿名类型,例如:

  var empData = from res in _db.EMPLOYEEs
where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
select new { res.EMAIL, res.USER_NAME };

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

就语法而言,我个人更喜欢方法链接

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

AFAIK,声明性 LINQ 语法在编译时被转换为类似的方法调用链。

更新

如果您想要整个对象,那么只需省略对 Select()的调用,即。

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

或者你可以用

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

说明:

  1. 从数据库中选择雇员作为 res。

  2. 根据 where 条件筛选员工详细信息。

  3. 通过使用 new {}创建匿名对象,从雇员对象中选择所需的字段