Need linq query to return only last 100 results

I am looking for a sql server database and apparently returning more than the application can handle. I am returning to a multitude of results, and I need to minimize the number of records sent, and then inform the user that they have chosen too many.

Here is what I have:

private List<Log> SearchLog()
{
  try
  {        
    using (var model = new SuburbanPortalEntities())
    {
      var qry = from logs in model.Logs
        where logs.LogDateTime > dateTimePicker_Start.Value &&
              logs.LogDateTime < dateTimePicker_End.Value
        select logs;

      Guid tokenid;
      if (Guid.TryParse(textBox_TokenId.Text, out tokenid))
      {
        qry = qry.Where(x => x.TokenId == tokenid);
      }

      if (!string.IsNullOrEmpty(textBox_SessionId.Text))
      {
        qry = qry.Where(x => x.SessionId == textBox_SessionId.Text.ToLower());
      }

      if (!string.IsNullOrWhiteSpace(textBox_Contains.Text))
      {
        qry = qry.Where(x => x.Message.Contains(textBox_Contains.Text));
      }

      if (checkedListBox_DisplayFilter.GetItemChecked(0))
      {
        qry = qry.Where(x => x.IsWarning);
      }

      if (checkedListBox_DisplayFilter.GetItemChecked(1))
      {
        qry = qry.Where(x => x.IsException);
      }

      var sourceEnumList = new List<string>();
      if (checkBox_WebPortal.Checked)
      {
        sourceEnumList.Add("WebPortal");
      }

      if (checkBox_SubService.Checked)
      {
        sourceEnumList.Add("SubService");
      }

      if (checkBox_TruckRouting.Checked)
      {
        sourceEnumList.Add("TruckRouting");
      }

      if (checkBox_SuburbanHub.Checked)
      {
        sourceEnumList.Add("SuburbanHub");

      }
      if (sourceEnumList.Any())
      {
        qry = qry.Where(x => sourceEnumList.Contains(x.SourceEnum));
      }

      qry = qry.OrderByDescending(x => x.LogDateTime);

      return qry.ToList();
    }

  }
  catch (Exception ex)
  {
    MessageBox.Show("Error: " + ex.Message);
    return null;
  }
}

How do I get LAST 100 entries and know to tell the user that they need to refine their search?

Thank!

+3
source share
3 answers

You can use the Takemethod

return qry.Take(100).ToList();

, 100 . , , . , OrderBy , :

return qry.OrderByDescending(x => x.LogDateTime).Take(100).ToList();
+9

100.

qry = qry.OrderBy(x => x.LogDateTime).Take(100).OrderByDescending(x => x.LogDateTime).ToList();

UPDATE:

, , , . : qry.Take(100).ToList(); ( )

+1 @Selman22

+2

.Take()

.

.Skip()

.

Skip Take, .Order(), , , .

, 100 , .Take(101) , 100

int page = 0;
int pageSize = 100
var result = dataset.OrderBy( x=> x.somecolumn ).Skip(page * 100).Take(pageSize + 1);

if(result.Count()>pageSize + 1)
     // there are more records than we can display
0

All Articles