0

I have a DataTable have all columns like:

B0_1 A1_1 B0_2 A1_2 B0_3 A1_3 B0_4 A1_4

How to count only columns start with A1_?

I had variably contains A1_x like this:

nameCol + n.ToString() + "_" +

Note: In this example you can see A1_1 -> A1_4 but 4 is randoms number, about from 1 -> 9.

Ave
  • 4,338
  • 4
  • 40
  • 67

3 Answers3

4

I suggest using Linq:

  DataTable table = ...

  int result = table.Columns
    .OfType<DataColumn>()
    .Count(column => column.ColumnName.StartsWith("A1_")); 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Thanks a lot... You awesome! – Ave Jul 27 '16 at 09:50
  • It would be better to use `.Cast()` instead of `.OfType()` because you don't need filter the elements. Read [here](http://stackoverflow.com/questions/4015930/when-to-use-cast-and-oftype-in-linq) the difference between these two methods. – Alberto Spelta Jul 27 '16 at 10:01
0

Regex is one option to match the post-fix restriction (A1_x with 1 < x < 9):

DataTable dt = new DataTable();
dt.Columns.Add("A1_a"); // out
dt.Columns.Add("A1_6"); // in
dt.Columns.Add("A1_5"); // in
dt.Columns.Add("A1_7"); // in
dt.Columns.Add("A1_0"); // out
dt.Columns.Add("A1_1"); // out
dt.Columns.Add("A1_9"); // out

// count result is: 3

var count = (from col in dt.Columns.OfType<DataColumn>()
             where Regex.IsMatch(col.ColumnName, "A1_[2-8]")
             select col).Count();

You need to add using System.Text.RegularExpressions; to use the Regex type.

Zein Makki
  • 29,485
  • 6
  • 52
  • 63
0

Using LINQ

int count = table.Columns.Cast<DataColumn>()
                  .Count(c => c.ColumnName.StartsWith("A1_"));

Using foreach

int count = 0;
foreach(DataColumn dc in table)
{
    if (dc.ColumnName.StartsWith("A1_"))
        count++;
}
Alberto Spelta
  • 3,578
  • 2
  • 21
  • 20
Imad
  • 7,126
  • 12
  • 55
  • 112