Im trying to do foreach for my purposes.
My scenerio looks like this:
I have a list and it looks like this (with only two values, 255 and 0):
List<int> list = new List<int>(){ 255, 0, 0, 255, 0, 255, 255, 0, 255 };
And a loop:
foreach(var item in list)
{
if(item == 255)
{
counter++; //its simple 'int' varialbe
summary += secondList.Contains(item); //its second list with ints
}
}
My secondList
looks like this:
static List<int> secondList= new List<int>(){ 128, 1, 2, 64, 0, 4, 32, 16, 8 };
What i want to do, is according to index of item
add value with the same place from secondList
.
If index of item == 1, i want to set secondList to position "1" too and add its value to summary
variable.
As i know, Contains
will return first item as item
but like you see, in list
i storage only two values, 255 and 0.
Is it possible to get the index of item
in foreach
loop properly?
Either declare a variable that will hold the index , or use a foor loop instead:
int idx = 0;
foreach(var item in list)
{
if(item == 255)
{
counter++; //its simple 'int' varialbe
summary += secondList[idx];
}
idx++;
}
Simplest solution is to use for
loop.
int counter = 0;
int summary = 0;
List<int> list = new List<int>() { 255, 0, 0, 255, 0, 255, 255, 0, 255 };
List<int> secondList = new List<int>() { 128, 1, 2, 64, 0, 4, 32, 16, 8 };
for (int i = 0; i < list.Count; i++)
{
if (list[i] == 255)
{
counter++; //its simple 'int' varialbe
summary += secondList[i]; //its second list with ints
}
}
You could also use a more functional approach, like
List<int> list = new List<int>(){ 255, 0, 0, 255, 0, 255, 255, 0, 255 };
List<int> secondList= new List<int>(){ 128, 1, 2, 64, 0, 4, 32, 16, 8 };
var matches = list.Zip(secondList, Tuple.Create)
.Where(t => t.Item1 == 255)
.Select(t => t.Item2);
Console.WriteLine(matches.Count());
Console.WriteLine(matches.Sum());
Output:
5
236
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.