1

我有这个过滤交易的 Linq 语句。它在过滤时工作正常,但是当没有返回任何内容时,我在 dt.AsEnumerable() 中收到错误。

错误是数据不包含行。有没有人知道什么时候没有退货怎么处理?

      newDataTable = dt.AsEnumerable()
                    .Where(r => !ListLinkedIds.Contains(r.Field<int>("LinkedTicketId")))
                    .CopyToDataTable();  

      gvMain.DataSource = newDataTable;
      gvMain.DataBind();
4

2 回答 2

3

You cannot use CopyToDataTable if the input sequence is empty. So you need to check that first:

var newDataTable = dt.Clone();  // an empty table with the same schema
var ticketRows = dt.AsEnumerable()
    .Where(r => !ListLinkedIds.Contains(r.Field<int>("LinkedTicketId")));
if(ticketRows.Any())
    newDataTable = ticketRows.CopyToDataTable();

Possible exceptions with CopytoDataTable

  • ArgumentNullException
    The source IEnumerable sequence is null and a new table cannot be created.
  • InvalidOperationException
    • A DataRow in the source sequence has a state of Deleted.
    • The source sequence does not contain any DataRow objects.
    • A DataRow in the source sequence is null.
于 2013-08-02T20:28:58.167 回答
0

DataTable在调用之前检查您是否有任何行AsEnumerable()

    if (dt.Rows.Count > 0)
    {
      newDataTable = dt.AsEnumerable()
                    .Where(r => !ListLinkedIds.Contains(r.Field<int>("LinkedTicketId")))
                    .CopyToDataTable();  

      gvMain.DataSource = newDataTable;
      gvMain.DataBind();
    }
    else {
    //error
    }
于 2013-08-02T20:16:57.620 回答