Use LINQ to check if all values ​​are "0"?

I have a simple data type:

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 line 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 bool (true) response only if:

All column values ​​whose name ends with "_a" have a value of 0

So I have to get False . What for?

Becuase

 John_a has 0 Paul_a has 0 

but

"Yoko_a" (which also ends with "_a" ) does not have a "0", but a different number.

What 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 returns True ....

What am I missing?

+4
source share
1 answer

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 checks all rows of a DataTable , I suggested that this is what you want. Enumerable.All returns false as soon as one comparison returns false .

Edit

I need to check only the first line.

Then it is even simpler:

 bool allZero = dt.Columns.Cast<DataColumn>() .Where(c => c.ColumnName.EndsWith("_a", StringComparison.OrdinalIgnoreCase)) .All(c => dt.Rows[0].Field<int>(c) == 0); 
+6
source

Source: https://habr.com/ru/post/1491685/


All Articles