List.Clear()清除我不希望它的列表

时间:2013-04-26 11:55:32

标签: c# .net

我想知道为什么我的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();
    }
}

2 个答案:

答案 0 :(得分:6)

由于ManhattanDistanceList.Add(i, tempList);添加了对同一列表tempList所指向的引用,因此当您稍后清除tempList指向的列表时,ManhattanDistanceList[i]也会被清除。

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

答案 1 :(得分:3)

因为你要将列表对象添加到字典中,然后你要清除你添加的同一个对象。

你想要的是:

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();
        }
    }

养成在需要它们的范围内声明变量的习惯,你不会经常遇到这类问题。