以下是代码: -
如何初始化data
?
var data;
if (mode == "view")
{
data = (from a in ctx.tblEmployee
where a.CompanyId == companyId
join b in ctx.tblTO_ShiftSchedule on a.Id equals b.EmployeeId
where b.CompanyId == companyId
select new { a, b, c, d }).ToList();
}
else
{
data = (from a in ctx.tblEmployee
where a.CompanyId == companyId
select new { a, b, c, d }).ToList();
}
答案 0 :(得分:7)
您无法初始化匿名类型,因此:
var data = mode == "view"
? (from a in ctx.tblEmployee
where a.CompanyId == companyId
join b in ctx.tblTO_ShiftSchedule on a.Id equals b.EmployeeId
where b.CompanyId == companyId
select new { a, b, c, d }).ToList()
: (from a in ctx.tblEmployee
where a.CompanyId == companyId
select new { a, b, c, d }).ToList();
答案 1 :(得分:0)
您的查询中的变量c和d(以及第二部分中的b)未定义,因此我有点猜测您想要实现的目标。因此我的代码不完整。
你需要一个辅助方法:
IEnumerable<T> GetDefaultEnumerable<T>(T instance)
{
return Enumerable.Empty<T>();
}
然后使用匿名类型的虚拟对象初始化数据
var data = GetDefaultEnumerable(new { a = new tblEmployee(), b = new tblTO_ShiftSchedule(), c = ..., d = ... });
但是,在大多数情况下,使用普通类型应该更清楚。如果可能,您还可以考虑将条件重构为查询。
答案 2 :(得分:0)
您无法初始化匿名类型 如果您了解从linq查询中获得的结构,我建议您创建一个命名结构 例如
class Data
{
Public Property A {get; set;}
Public Property B {get; set;}
Public Property C {get; set;}
Public Property D {get; set;}
}
并修改现有代码,使其如下所示
var data = List<Data>;
if (mode == "view")
{
data = (from a in ctx.tblEmployee
where a.CompanyId == companyId
join b in ctx.tblTO_ShiftSchedule on a.Id equals b.EmployeeId
where b.CompanyId == companyId
select new Data with { A=a, B=b, C=c, D=d }).ToList();
}
else
{
data = (from a in ctx.tblEmployee
where a.CompanyId == companyId
select new Data with { A=a, B=b, C=c, D=d }).ToList();
}
If