Search code examples
c#findpseudocode

Find every 'first field in a combination of 3 fields' in a row and skip the first field


How can I find every 'first field in a combination of 3 fields' in a row while skipping the first field of the row.

Assume we have a row like this:

"Zero", "One", "Two", "Three", "One", "Two", "Three", "One", "Two", "Three"

I want to make a loop and then only do something when the value is "One" in this case, however the values differ from each other of course.

Note that I have to skip "Zero"

I need it in C# but other language or Pseudo code is OK as well

Please let me note that I can do it with 2 loops, but I don't think that is the most efficient way.


Solution

  • So this is a DataTable and you want to skip the first column and take every third column:

    List<DataColumn> myColumns = table.Columns.Cast<DataColumn>()
        .Skip(1)
        .Select((col, index) => new { col, index})
        .GroupBy(x => x.index / 3)
        .Select(xg => xg.Select(x => x.col).First())
        .ToList();
    

    This uses the integer division "trick" to get a group of three rows. Then i take the first row of each group.

    foreach (DataRow row in table.Rows)
            Console.WriteLine("Every third field after the second: "
                + string.Join(",", myColumns.Select(c => row[c])));