Reputation: 545
I have a DataTable which I want to query one column at a time to check if it meets the set criteria, for some reason the below code gives correct results for the first column after that the results are incorrect.
private bool BusinessRulesOne(DataTable dt, DataColumn dc)
{
bool isSatisfied = false;
DataRow[] checkColumn = dt.Select(dc.ColumnName + " " + "in (1,2,3,)");
if (checkColumn.Length != 0)
{
isSatisfied = true;
}
return isSatisfied;
}
On this method Im passing the DataTable I'm querying and DataColumn that I'm currently concentrating on. What needs to happen here is that I want to check if the values on this column consists of the values 1,2 and 3. If yes then return true.
private bool BusinessRulesTwo(DataTable dt, DataColumn dc)
{
bool isSatisfied = false;
var checkColumn = dt.Select(dc.ColumnName + " " + " = 1");
if (checkColumn.Count() > 3)
{
isSatisfied = true;
}
return isSatisfied;
}
On the other rule I'm checking if the number of one's (1's) in that column are more than three(3) if yes return true.
Any suggestions are welcome, I'm not clued up with Linq but willing to learn and explore it if it makes life easier.
Edit With Values in One column
Upvotes: 0
Views: 5801
Reputation: 1507
At first you should know that data table doesn't implement IEnumerable so to use Linq here you should use AsEnumerable: For the first rule:
private bool BusinessRulesOne(DataTable dt, DataColumn dc) { return dt.AsEnumerable().Any(dataRow => !String.IsNullOrEmpty(dataRow.Field<string>(dc.ColumnName).First().ToString()) && ( dataRow.Field<int>(dc.ColumnName) == 1 || dataRow.Field<int>(dc.ColumnName) == 2 || dataRow.Field<int>(dc.ColumnName) == 3));}
For the second rule:
private bool BusinessRulesTwo(DataTable dt, DataColumn dc) { return dt.AsEnumerable().Where(dataRow => !String.IsNullOrEmpty(dataRow.Field<string>(dc.ColumnName).First().ToString()) && ( dataRow.Field<int>(dc.ColumnName) == 1)).Count() > 3 ;}
Upvotes: 2
Reputation: 35680
"if the values on this column consists of the values 1,2 and 3, then return true"
BusinessRulesOne
doesn't express this condition properly. It works differently: "if column contains at least one value from set, then return true". It doesn't guarantee what there are no other values.
here is modified method with inverted logic: "if this column contains smth except 1,2 or 3, then return false"
private bool BusinessRulesOne(DataTable dt, DataColumn dc)
{
DataRow[] checkColumn = dt.Select(dc.ColumnName + " not in (1,2,3)");
return checkColumn.Length == 0;
}
Upvotes: 2