如果你想检查一个数据集合是否具有一定的价值,你可以在Linq中使用Any()方法。
Linq 方法语法(带 lambda 表达式)
Dim foundCell_1 = dt_aa.AsEnumerable.Any(Function (x) x.Field(Of String)("cell_1") = textBox1.Text)
If foundCell_1 Then
XtraMessageBox.Show("Cell_1 already exist !", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
If Not foundCell_1 Then
Dim foundCell_2 = dt_aa.AsEnumerable.Any(Function(x) x.Field(Of String)("cell_2") = textBox2.Text)
If foundCell_2 Then
XtraMessageBox.Show("Cell_2 already exist !", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End If
Linq 查询语法
Dim foundCell_1 = (From rows In dt_aa.AsEnumerable
Where rows.Field(Of String)("cell_1") = textBox1.Text).Any
If foundCell_1 Then
XtraMessageBox.Show("Cell_1 already exist !", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
If Not foundCell_1 Then
Dim foundCell_2 = (From rows In dt_aa.AsEnumerable
Where rows.Field(Of String)("cell_2") = textBox2.Text).Any
If foundCell_2 Then
XtraMessageBox.Show("Cell_2 already exist !", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End If
如果不想使用Linq,可以使用DataTable中的Select()方法。
Dim foundCell_1 = dt_aa.Select("cell_1 = '" & textBox1.Text & "'").Length > 0
If foundCell_1 Then
XtraMessageBox.Show("Cell_1 already exist !", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
If Not foundCell_1 Then
Dim foundCell_2 = dt_aa.Select("cell_2 = '" & textBox2.Text & "'").Length > 0
If foundCell_2 Then
XtraMessageBox.Show("Cell_2 already exist !", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End If
Linq Any() 方法可能执行得更快,因为如果元素匹配条件,它会返回 true,因此它不需要检查所有数据。
注意:我假设 cell_1 和 cell_2 都是字符串。