通过多个语句过滤数据表

我有一个名为Designs


我根据从用户收到的值列表过滤此表


List<Guid> values = new List<Guid>();


foreach (var checkbox in cbo)

{

    //logic to fill list...

}

一旦我这样做了,我就会使用 LINQ 过滤我的数据表:


designs = Designs.AsEnumerable()

       .Where(row => values.Contains(row.Field<Guid>("DesignGroupId"))).CopyToDataTable();

而且效果非常好。但现在我想在查询中添加一个条件。我想要获得具有 field 的列"DesignKey" = null。所以我尝试:


designs = Designs.AsEnumerable()

       .Where(row => values.Contains(row.Field<Guid>("DesignGroupId")) && row.Field<int>("DesignKey") == null).CopyToDataTable();

但我得到一个例外:


System.InvalidOperationException:“源不包含 DataRows。”


我究竟做错了什么?问候


米琪卡哇伊
浏览 109回答 2
2回答

www说

首先要知道哪个方法抛出异常。在您的情况下,CopyToDatabase 方法将抛出此异常,如下所述:无效操作异常源序列不包含任何 DataRow 对象。为了确保这一点,您可以拆分您的请求:var designEnum= Designs.AsEnumerable();var firstSelect = designEnum.Where(row => values.Contains(row.Field<Guid>("DesignGroupId"));var secondSelect = firstSelect.Where(row => row.Field<int>("DesignKey") == null);if (secondSelect.Count == 0){    //Handle the fact that you have no data    design = null;}else{    designs = secondSelect.CopyToDataTable();}而且这更容易调试,因为您可以使用调试器逐行进行调试。您可以稍后压缩代码。

达令说

你不能 CopyToDataTable null这对你有用:void Main(){&nbsp; &nbsp; DataTable Designs = new DataTable();&nbsp; &nbsp; Designs.Columns.Add("DesignGroupId", typeof(Guid));&nbsp; &nbsp; Designs.Rows.Add(Guid.NewGuid());&nbsp; &nbsp; Designs.Rows.Add(Guid.NewGuid());&nbsp; &nbsp; Designs.Rows.Add(Guid.NewGuid());&nbsp; &nbsp; Designs.Rows.Add(Guid.Parse("7c176832-593c-402f-9def-fbe12da3742f"));&nbsp; &nbsp; List<Guid> values = new List<Guid>();&nbsp; &nbsp; values.Add(Guid.NewGuid());&nbsp; &nbsp; values.Add(Guid.NewGuid());&nbsp; &nbsp; values.Add(Guid.NewGuid());&nbsp; &nbsp; //values.Add(Guid.Parse("7c176832-593c-402f-9def-fbe12da3742f"));&nbsp; &nbsp; var res = Designs.AsEnumerable().Where(row => values.Contains(row.Field<Guid>("DesignGroupId"))).ToList();&nbsp; &nbsp; &nbsp; if (res.Count > 0 )&nbsp; &nbsp; &nbsp; &nbsp; Designs =&nbsp; res.CopyToDataTable();&nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; Designs.Clear();}
打开App,查看更多内容
随时随地看视频慕课网APP