根据linq查询中检索到的其他几个“列”设置状态的最佳做法是什么。
var result = (from q in query
select new Item
{
ApprovedDate = q.ApprovedDate,
CreatedDate = q.CreatedDate,
DeclinedDate = q.DeclinedDate,
Status = 0
});
我想将状态设置为0,1,2。
(ApprovedDate == null and DeclinedDate == null) --> 0
(ApprovedDate != null and DeclinedDate == null) --> 1
(DeclinedDate != null) --> 3
或许类似于:
var result = (from q in query
select new Item
{
ApprovedDate = q.ApprovedDate,
CreatedDate = q.CreatedDate,
DeclinedDate = q.DeclinedDate,
Status = (q.CreatedDate == null && q.DeclinedDate == null) ? 0 : (q.ApprovedDate != null && q.DeclinedDate == null) ? 1 : 2
});
我可能会添加更多的状态组合,所以我应该尝试在linq select查询中,在我的存储库对象中执行此操作。或者稍后在控制器中我将执行.ToList()然后预览列表设置正确的状态代码?
如果有超过3个状态代码,则linq查询会“难以”阅读。
答案 0 :(得分:2)
如何将状态计算移动到Item
级?如果status属性依赖于其他属性值,那么它肯定是计算属性:
var result = from q in query
select new Item
{
ApprovedDate = q.ApprovedDate,
CreatedDate = q.CreatedDate,
DeclinedDate = q.DeclinedDate
});
和
public class Item
{
// other properties
public int Status
{
get
{
if (ApprovedDate == null and DeclinedDate == null)
return 0;
if (ApprovedDate != null and DeclinedDate == null)
return 1;
if (DeclinedDate != null)
return 3;
// etc
}
}
}
实际上我认为这是最好的选择,因为在这种情况下,状态计算逻辑将接近所需的数据。如果(出于某种原因)您无法使用此方法,请将设置状态移至本地项目集合:
var items = result.ToList().ForEach(i => i.Status = CalculateStatus(i));
答案 1 :(得分:0)
也许包裹在一个函数中一个像这样做的linq
var result = (from q in query sele q).AsEnumerable()
.Select( x => new Item()
{
ApprovedDate = x.ApprovedDate,
CreatedDate = x.CreatedDate,
DeclinedDate = x.DeclinedDate,
Status = MyStatusFunction(x.CreatedDate,q.DeclinedDate)
});
public int MyStatusFunction(DateTime ApprovedDate , Datetime DeclinedDate)
{
if (ApprovedDate == null and DeclinedDate == null) return 0;
else if(ApprovedDate != null and DeclinedDate == null) return 1;
else if (DeclinedDate != null) return 3;
}