从具有多个条件的DataTable中选择

时间:2014-01-16 05:38:22

标签: c# linq

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

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);
     }
}

以上内容并没有给我最新的条目。

3 个答案:

答案 0 :(得分:0)

您可能需要使用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();
}

答案 1 :(得分:0)

试试这个

    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 :(得分:0)

试试这个

 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();
         }
    }