简体   繁体   English

检查数据表是否包含某个值

[英]check if datatable contains certain value

I tried to check, if my datatable created before from sql select contains number equal to my NumericUpDown.我试图检查我之前从 sql select 创建的数据表是否包含等于我的 NumericUpDown 的数字。 'table' was created by sqldatareader with Fill 'table' 是由 sqldatareader 使用 Fill 创建的

var table = new DataTable();
var da = new SqlDataAdapter("select id from table3 where typ in (0,1)", connectionString);
                
da.Fill(table);

Table is very simple:表很简单:

id
2
3
5

what i tried (nudNrArk is my numericUpDown):我尝试了什么(nudNrArk 是我的 numericUpDown):

if (table.AsEnumerable().Any(s => s.Equals(nudNrArk.Value)))

if (table.AsEnumerable().Where(c => c.Field<int>("id").Equals(nudNrArk.Value)).Count() > 0)

those both never return true那些都永远不会返回真

if (table.Rows.Contains(nudNrArk.Value)) this (looks as simplest way) want a primary key if (table.Rows.Contains(nudNrArk.Value))这个(看起来最简单的方法)想要一个主键

Is there a simple way to add primary key to column in this table?有没有一种简单的方法可以将主键添加到该表中的列? Or better way to check this?或者更好的方法来检查这个?

First of all this is low explained question it is not clear what you want.首先,这是一个低解释的问题,不清楚你想要什么。

This should be work:这应该是工作:

   if (table.AsEnumerable().Where(c => c.Field<int>("id").Equals(nudNrArk.Value)).Count() > 0)

So question is what is nudNrArk.Value is property Value type int, string or object?那么问题是什么是 nudNrArk.Value 是属性值类型 int、string 还是 object? Try with this:试试这个:

 if (table.AsEnumerable().Where(c => c.Field<int>("id") == (int)nudNrArk.Value).Count() > 0)

Equals won't work if they are not same type, if you want to compare two objects you should override Equals method of class and write your own method for Equals.如果它们不是同一类型,Equals 将不起作用,如果要比较两个对象,则应覆盖 class 的 Equals 方法并为 Equals 编写自己的方法。

Edit:编辑:

This is way to add primary key on datatable:这是在数据表上添加主键的方法:

table.PrimaryKey = new DataColumn[] { table.Columns["id"]};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM