且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Linq过滤数据表

更新时间:2023-01-29 19:41:48

我们需要做一些基本的问题解决:声明一个临时变量



We need to do some basic breaking down of the problem: Declare a temporary variable

var foo = from myRow in dtInventory.AsEnumerable() select myRow;



在上面设置一个断点并执行,如果foo有行,那么你有一个不同的问题,所以继续。依靠有数据的表是没有用的。虽然我怀疑这是你的问题,你只需在结果中获得null或空值

步骤2是替换字母[0] .ToString()带* any *字母,例如a(根据Kuthuparakkal建议)。如果你没有得到异常,你的数组至少是空的。



如果你得到一个例外,那么问题是 myRow.Field< string>(Description)返回null。然后你有两个立即调查的罪魁祸首:要么你的字段名称不匹配(区分大小写?)或者字段本身允许为null(循环未过滤的结果并依次获取每个值)。





如果所有这些都无法诊断您的问题,那么跳出来的唯一另一件事就是 dtInventory.AsEnumerable(),如果这导致 myRow 丢失它的列信息/上下文, .Field< t>< / t> 不起作用。鉴于代码构建,这非常不太可能(我没有使用过这种方法),但你可以尝试重新删除 where 子句和循环遍历未过滤的结果,依次检查每个 DataRow 对象。


Put on a breakpoint on the above and execute, if foo has rows then you've a different problem so move on. Relying on the table having data is no good. Though I doubt this is your problem, you just get a null or empty value in result
Step 2 is to replace letters[0].ToString() with *any* letter, e.g. "a" (as per Kuthuparakkal suggestion). If you don't get the exception, your array is null at the very least.

If you do get an exception then the problem is myRow.Field<string>("Description") is returning null. You've then got two immediate culprits to investigate: either your field name doesn't match (case sensitive?) or the field itself allows null (loop over the unfiltered results and get each value in turn to see).


If all this fails to diagnose your problem, the only other thing that leaps out is the dtInventory.AsEnumerable(), if this causes myRow to lose the it's column information/context, the .Field<t></t> won't work. This is very unlikely (I've not used this method) given that your code builds, but you could try re-removing the where clause and looping through the unfiltered results, inspecting each DataRow object in turn.