I have List<int>
, where are write Numbers, from 0-1, now I need
- find the first item which will contain the number “1”,
- I NEED to save this item in the variable,
- then I need compare this Variable to another item in list….
So my problem is: how can I save this variable, then compare it to another item in the list, BUT without replacing this variable by a List?
public static void Main()
{
List<int> list = new List<int>();
list.Add(0);
list.Add(0);
list.Add(1);
list.Add(1);
list.Add(0);
list.Add(0);
list.Add(1);
for (int i = 0; i < list.Count-1; i )
{
int temp;
int count = 0;
if (list[i]>=1)
{
temp =list[i];
if (temp == list[i 1])
{
count ;
}
}
}
}
CodePudding user response:
Define a variable with initial value (ex. -1). As long as the value is -1 this means the index not found yet. So, try the following:
// The index of first value of 1 in the list. -1 means not found yet
int indexFound = -1;
List<int> list = new List<int>();
list.Add(0);
list.Add(0);
list.Add(1);
list.Add(1);
list.Add(0);
list.Add(0);
list.Add(1);
for (int i = 0; i < list.Count-1; i )
{
// condition will not execute if first item with value 1 already found
if (list[i] == 1 && indexFound == -1)
{
indexFound = i; // index of first value in list = 1
}
// compare the found value with any element in the list during the looping. Rephrase the condition as needed according to comparison required
if (list[i] == indexFound)
{
Console.WriteLine("comparison of this Variable to another item in list");
// do whatever needed
}
}
Console.WriteLine(indexFound);