使用Linq过滤数据表 [英] Filter in Data table using Linq

查看:76
本文介绍了使用Linq过滤数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在使用此linq来过滤数据表中的行。

Hi All,
I am using this linq to filter rows from data table.

var result = from myRow in dtInventory.AsEnumerable()
 where myRow.Field<string>("Description").StartsWith(letters[0].ToString(), StringComparison.OrdinalIgnoreCase)
select myRow;







当从SQL表中填充dtInventory时,Query工作正常。但是当我通过SQL视图填充数据表时,查询抛出异常就像



对象引用没有设置为对象的实例





如何解决问题??





问候,

Palraj M.




when the dtInventory is filled from a SQL table the Query works fine. but when I fill data table by SQL view the Query Throw exception like

"Object reference not set to an instance of an object"


How to resolve the issue??


Regards,
Palraj M.

推荐答案

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



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.


这篇关于使用Linq过滤数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆