2014-01-16 26 views
2

我想從某個特定帳號的數據表中選擇一行,並在設定的日期時間之前或等於最近的日期。我想下面的,但只有最近一次入境看起來是這樣的我想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); 
    } 
} 

上面沒有給我最近的條目。

回答

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


    } 
} 
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(); 
} 
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(); 
     } 
    } 
相關問題