1

根据在 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 选择查询中执行此操作,在我的存储库对象中。或者稍后在控制器中执行 .ToList() 然后 foreach 列表来设置正确的状态码?

甚至超过 3 个状态码,linq 查询变得“难以”阅读。

4

2 回答 2

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));
于 2012-11-12T20:33:31.320 回答
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;
}
于 2012-11-12T20:33:45.473 回答