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

StackOverflow https://stackoverflow.com/questions/22686898

  •  22-06-2023
  •  | 
  •  

سؤال

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.

هل كانت مفيدة؟

المحلول

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])));

نصائح أخرى

use the modulo operator.

Pesudocode:

for (int i = 1; i < row.length; i++)
{
    if (i+2 % 3 == 0) doSomething();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top