list . clear()清除一个列表,我不希望它这么做

本文关键字:希望 列表 清除 clear list 一个 | 更新日期: 2023-09-27 18:10:56

我想知道为什么我的templist.clear()方法清除了我添加到ManhattanDistance字典中的列表。

在这方面的任何帮助将是非常感激的,这是我的数据挖掘项目的一部分,我一直在工作。我必须使用k最近邻方法来估算缺失值。

public void CalculateManhattanDistance(Dictionary<int, List<string>> MissingList, Dictionary<int, List<string>> OtherList)
{
    Dictionary<int,Array> MissingListNeighbours = new Dictionary<int,Array>();
    Dictionary<int, List<int>> ManhattanDistanceList = new Dictionary<int,List<int>>();
    List<int> tempList = new List<int>();
    int total=0;
    int k=0;
    try
    {
        for (int i = 0; i < MissingList.Count(); i++)
        {
            for (int j = 0; j < OtherList.Count(); j++)
            {
                for (k = 0; k < MissingList[0].ToArray().Length; k++)
                {
                    if (Convert.ToChar(MissingList[i][k].ToString()) == '?')
                        continue;
                    else
                        total += Math.Abs(Convert.ToInt32(MissingList[i][k].ToString()) - Convert.ToInt32(OtherList[j][k].ToString()));
                }
                tempList.Add(total);
                total = 0;
            }
            ManhattanDistanceList.Add(i, tempList);
            tempList.Clear();
        }
    }
    catch (Exception ex)
    {
          ex.Message.ToString();
    }
}

list . clear()清除一个列表,我不希望它这么做

因为ManhattanDistanceList.Add(i, tempList);添加了一个引用到tempList指向的相同列表,所以当您稍后清除tempList指向的列表时,ManhattanDistanceList[i]也被清除。

将其更改为ManhattanDistanceList.Add(i, tempList.ToList());以添加列表的副本

因为你将list对象添加到字典中然后你将清除添加的相同对象

你想要的是:

public void CalculateManhattanDistance(Dictionary<int, List<string>> MissingList, Dictionary<int, List<string>> OtherList)
    {
        Dictionary<int,Array> MissingListNeighbours = new Dictionary<int,Array>();
        Dictionary<int, List<int>> ManhattanDistanceList = new Dictionary<int,List<int>>();
        try
        {
            for (int i = 0; i < MissingList.Count(); i++)
            {
                List<int> tempList = new List<int>();
                for (int j = 0; j < OtherList.Count(); j++)
                {
                    int total=0;
                    for (int k = 0; k < MissingList[0].ToArray().Length; k++)
                    {
                        if (Convert.ToChar(MissingList[i][k].ToString()) == '?')
                            continue;
                        else
                            total += Math.Abs(Convert.ToInt32(MissingList[i][k].ToString()) - Convert.ToInt32(OtherList[j][k].ToString()));

                    }
                    tempList.Add(total);
                }
                ManhattanDistanceList.Add(i, tempList);
            }
        }
        catch (Exception ex)
        {
              ex.Message.ToString();
        }
    }

养成在需要变量的范围内声明变量的习惯,这样你就不会经常遇到这种问题了。