用变量值在C#中填充一个空库

问题描述 投票:0回答:1

只是一个简单的问题。我很难将变化的变量的值存储在列表或数组中。不断变化的变量是movingPointIdx,但是它不存储值并对其进行排序

List<int> listXpoints = new List<int>();
listXpoints.Add(movingPointIdx); //movingPointIdx: int variable, which takes different values 

listXpoints.Sort();
foreach  (int i in listXpoints)
{
    Console.WriteLine(i);
}
c#
1个回答
0
投票

让我猜想...您是否在函数中使用局部变量并一直对其进行初始化?..

检查示例,请:Code sample


-1
投票

1。当变量不断变化时,不要每次都初始化列表]]

2。在将其推送到列表之前,请检查您不断变化的变量是否已存在于列表中]

3。如果列表中不存在,则将其推入列表并对列表进行排序并打印

您的代码应类似于:

List<int> listXpoints = new List<int>(); //declare globally

//when your variable changes call this logic
if(!listXpoints.Any(x => x == movingPointIdx)){
    listXpoints.Add(movingPointIdx); 
    Console.Clear();
    listXpoints.Sort();
    foreach  (int i in listXpoints)
    {
        Console.WriteLine(i);
    }
}

我希望这可以帮助...

© www.soinside.com 2019 - 2024. All rights reserved.