2014-01-16 3 views
2

Я пытаюсь выбрать строку из datatable с определенным номером учетной записи и самой последней датой до или равной заданному дате. Я хочу ниже, но только последняя запись, так что кажется, что я хочу использовать FirstOrDefault() или SingleOrDefault() после currentDateTime (т.е. ... < = currentDateTime.FirstOrDefault())Выберите из DataTable с несколькими условиями

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(); 
     } 
    } 
Смежные вопросы