简体   繁体   中英

How can I get element of list

I have an array with 3 elements, I use for -loop to remove "1", "2" but if -condition always false. What's the problem?

string[] listCountAnwser = {"1", "2", "3"};
List<string> listCountAnwsers = new List<string>(listCountAnwser);
for (int i = 0; i < listCountAnwsers.Count; i++)
{
    if (Int32.Parse(listCountAnwsers[i]) < Int32.Parse(listCountAnwsers[i++]))
    {
        listCountAnwsers.Add(listCountAnwser[i]);
    }
}

A few things caught my eye.
At first, you are wrong to use the increment operator. To make sure run this code:

for (int i = 0; i < listCountAnwsers.Count; i++)
    Console.WriteLine(listCountAnwsers[i] + "\t" + listCountAnwsers[i++]);

The output will be like:

1    1
3    3

That is why your code never enters the if -condition.
Another problem is that you remove elemets. This entails changing the listCountAnwsers.Count property of list. To make sure:

for (int i = 0; i < list.Length; i++)
{
    listCountAnwsers.Remove(listCountAnwsers[i]);
    Console.WriteLine(listCountAnwsers.Count);
}

The output :

2
1

Then the exception like argument out of range . Indeed. Also you can get such exception when you will try something like this:

if (Int32.Parse(listCountAnwsers[i]) < Int32.Parse(listCountAnwsers[i + 1]))
    listCountAnwsers.Remove(listCountAnwser[i]);

So the solving of your problem depends on what you need at all. What elements do you want to have at the result? Please clarify

try this. i++ increase the value of i after check in the condition. So you need to use i+1

string[] listCountAnwser = {"1", "2", "3"};
List<string> listCountAnwsers = new List<string>(listCountAnwser);
for (int i = 0; i < listCountAnwsers.Count; i++)
{
    if (Int32.Parse(listCountAnwsers[i]) < Int32.Parse(listCountAnwsers[i+1]))
    {
        listCountAnwsers.Add(listCountAnwser[i]);
     }
 }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM