C# Linq语法-选择多个列
这是我用于实体模型的Linq语法C# Linq语法-选择多个列,c#,linq,entity-framework,C#,Linq,Entity Framework,这是我用于实体模型的Linq语法 IQueryable<string> objEmployee = null; objEmployee = from res in _db.EMPLOYEEs where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo) select res.EMAIL; IQueryable对象员工=null; OBJEEMPLOYEE=来自数据库
IQueryable<string> objEmployee = null;
objEmployee = from res in _db.EMPLOYEEs
where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
select res.EMAIL;
IQueryable对象员工=null;
OBJEEMPLOYEE=来自数据库中的资源
其中(res.EMAIL==givininfo | | res.USER_NAME==givininfo)
选择res.EMAIL;
如何选择多个列?就像我也想选择res.ID一样。我怎样才能收到这些?我想IQueryable是行不通的。
这被称为Linq to SQL-对吗?您可以使用匿名类型,例如:
var empData = from res in _db.EMPLOYEEs
where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
select new { res.EMAIL, res.USER_NAME };
正如其他答案所指出的,您需要使用匿名类型 就语法而言,我个人更喜欢方法链接。链接等效方法为:-
var employee = _db.EMPLOYEEs
.Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo)
.Select(x => new { x.EMAIL, x.ID });
另外,声明性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 {email=res.EMAIL, username=res.USERNAME} );
说明:
LinqToSql和实体框架是不同的。请参阅在答案中添加解释。如何访问不同的列?您能建议如何正确编写此表达式:选择new{(DateTime.Now-debt.ClaimDate),debt.Amount}?它抛出一个错误:无效的匿名类型成员declarator@DainiusKreivys
选择新建{Diff=(DateTime.Now-debt.ClaimDate),Amount=debt.Amount}
。答案中使用的形式是一种简写形式,其中初始化表达式中的成员名用作匿名类型的字段名。例如,new{res.EMAIL,res.USER\u NAME}
是new{EMAIL=res.EMAIL,USER\u NAME=res.USER\u NAME}
的缩写。如果有一个表达式,比如日期-速记不适用,因此编译器会出错。
var employee = (from res in _db.EMPLOYEEs
where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
select new {email=res.EMAIL, username=res.USERNAME} );