【问题标题】:Select From DataTable with Multiple Conditions从具有多个条件的数据表中选择
【发布时间】:2014-01-16 13:52:56
【问题描述】:

我正在尝试从具有特定帐号且最近日期早于或等于设置日期时间的数据表中选择一行。我想要以下但只有最新的条目,所以我想在 currentDateTime 之后使用 FirstOrDefault() 或 SingleOrDefault() (即...

DateTime currentDateTime = firstDate;
while (firstDate <= lastDate)
{
     foreach (AccountCategory a in db.AccountCategories)
     {
         var result = Settings.dtCurrent.AsEnumerable()
               .Where(b => b.Field<string>("Account") == a.Account 
                         && (b.Field<DateTime>("Date") <= currentDateTime);
     }
}

上面没有给我最近的条目。

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    这样试试

        DateTime currentDateTime = firstDate;
        while (firstDate <= lastDate)
        {
             foreach (AccountCategory a in db.AccountCategories)
             {
                 var result = Settings.dtCurrent.AsEnumerable()
                       .Where(b => b.Field<string>("Account") == a.Account 
                                 && (b.Field<DateTime>("Date") <= currentDateTime).OrderByDescending(b=> b.Field<DateTime>("Date")).FirstOrDefault();
    
    
       }
    }
    

    【讨论】:

      【解决方案2】:

      您可能需要使用OrderByDescending 对记录进行排序,以使最少的记录排在最前面。然后您可以使用FirstOrDefault 获取第一条记录。

      foreach (AccountCategory a in db.AccountCategories)
      {
           var result = Settings.dtCurrent.AsEnumerable()
                 .Where(b => b.Field<string>("Account") == a.Account 
                           && (b.Field<DateTime>("Date") <= currentDateTime).OrderByDescending(r=>r.Field<DateTime>("Date")).FirstOrDefault();
      }
      

      【讨论】:

        【解决方案3】:

        试试这个

         DateTime currentDateTime = firstDate;
            while (firstDate <= lastDate)
            {
                 foreach (AccountCategory a in db.AccountCategories)
                 {
                     var result = Settings.dtCurrent.AsEnumerable()
                           .Where(b => b.Field<string>("Account") == a.Account 
                                     && (b.Field<DateTime>("Date") <= currentDateTime)
                           .OrderByDescending(b=> b.Field<DateTime>("Date"))
                           .FirstOrDefault();
                 }
            }
        

        【讨论】:

          猜你喜欢
          • 2010-12-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-04
          相关资源
          最近更新 更多