Reputation: 148524
I have a simple datatable :
DataTable dt = new DataTable("myTable");
dt.Columns.Add("id", typeof (int));
dt.Columns.Add("John_a", typeof (int));
dt.Columns.Add("Paul_a", typeof (int));
dt.Columns.Add("George_b", typeof (int));
dt.Columns.Add("Ringo_b", typeof (int));
dt.Columns.Add("Yoko_a", typeof (int));
it has one row with data :
DataRow r = dt.NewRow();
r["id"] = 1;
r["John_a"] = 0;
r["Paul_a"] = 0;
r["George_b"] =4;
r["Ringo_b"] = 2;
r["Yoko_a"] =10;
dt.Rows.Add(r);
I need to get a bool
answer ( true) only if :
All Values on columns whose name ends with "_a"
has value 0
So here , I should get False
. why ?
Becuase
John_a has 0
Paul_a has 0
but
"Yoko_a"
(which also ends with "_a"
) doesn't have "0" but another number.
What have i tried :
var t =
dt.AsEnumerable().Select(row => dt.Columns.Cast<DataColumn>()
.Where(c => c.ColumnName.ToLower().EndsWith("_a")
&& row.Field<int>(c.ColumnName) == 0
)
).Any();
but It returns True
....
What am I missing?
Upvotes: 4
Views: 4200
Reputation: 460068
As the name suggests, use Enumerable.All
:
bool allZero = dt.Columns.Cast<DataColumn>()
.Where(c => c.ColumnName.EndsWith("_a", StringComparison.OrdinalIgnoreCase))
.All(c => dt.AsEnumerable().All(r => r.Field<int>(c) == 0));
Note that this approach also check all rows of the DataTable
, i've asumed that this is what you want. Enumerable.All
returns false
as soon as one comparison returned false
.
Edit
I need only the first row to be checked.
Then it's even easier:
bool allZero = dt.Columns.Cast<DataColumn>()
.Where(c => c.ColumnName.EndsWith("_a", StringComparison.OrdinalIgnoreCase))
.All(c => dt.Rows[0].Field<int>(c) == 0);
Upvotes: 6