0

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

2 回答 2

6

Because ManhattanDistanceList.Add(i, tempList); adds a reference to the same list tempList is pointing to, so when you later clear the list tempList is pointing to, ManhattanDistanceList[i] also gets cleared.

Change it to ManhattanDistanceList.Add(i, tempList.ToList()); to add a copy of the list.

于 2013-04-26T11:58:22.263 回答
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();
        }
    }

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

于 2013-04-26T12:01:58.720 回答