Home > Software engineering >  Iterate a List<string> 12 by 12 and get the items
Iterate a List<string> 12 by 12 and get the items

Time:11-25

I have a generic list of strings, but I know from 12 to 12 items I have a Record. I Also have a Model that want to populate.

My primary code

for (int r = 2; r <= rows; r  )
{
    for (int c = 3; c <= cols; c  )
    {
        try
        {
            list.Add(usedRange.Cells[r, c].Value2.ToString());
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
}

foreach (string item in list)
{

}

So in foreach (string item in list) I know 12 the 24 then 36 my record is there

The problem is this peace of code

foreach (string item in list)
{
  p.LastName = item
}

I need a for in order to populate my Model with all 12 items, I'm stuck

CodePudding user response:

You can also get item each 12 elements with a for by index like this:

for (var i = 0; i < list.Count; i =12)
    var p.LastName = list[i];

CodePudding user response:

If you only want every 12th element, here is a Linq alternative to the classical for loops. It is not better or worst, but can be useful depending on the context.

var MyList = Enumerable.Range(0, 100); // Just an example list, containing numbers from 0 to 99.

var FilteredElements = MyList
    .Where((x, i) => i % 12 == 0);

foreach(var e in FilteredElements)
{
    Console.WriteLine(e);
}

Output:

0
12
24
36
48
60
72
84
96

Explanation:

.Where((x, i) => i % 12 == 0) is where the work is done. The linq extension method Where has an overload that takes as argument a Func<TSource, Int32, bool>. See the doc. The second parameter is the index of the element of the collection.

So .Where((x, i) => i % 12 == 0) keeps only the elements of the collection for which the index i is divisible by 12 (i % 12 == 0). Hence the result containing only multiples of 12.

  • Related