C#|在List集合为NULL时需要添加数据的处理方法

最近写了一个循环往字典的Value值添加数据的程序(字典的Value为一个List),经常碰到 “Object reference not set to an instance of an object”,就自己去了解了一下空集合和集合为NULL的区别,可以看看这篇文章《list集合为空或为null的区别》

理解区别之后,我们来看一下原来错误的代码:

Dictionary<int, List<string> >dic = new Dictionary<int, List<string>>();
int rowCount = ret_res.Rows.Count;
for (int index = 0; index < rowCount; index++)
{
    List<string> NewList = new List<string>();
    int NEAR_FID = Convert.ToInt32(ret_res.Rows[index]["NEAR_FID"]);
    if (dic.TryGetValue(NEAR_FID, out NewList))
    {
        List<string> tempList = new List<string>();
        tempList = dic[NEAR_FID];
        int tempnum = int.Parse(tempList.First());
        tempnum++;
        string IN_FID = ret_res.Rows[index]["IN_FID"].ToString();
        tempList[0] = tempnum.ToString();
        tempList.Add(IN_FID);
        dic[NEAR_FID] = tempList;
        //dic.Add(NEAR_FID, new List<string>(tempList));
        tempList.Clear();
    }
    else
    {
        int num = 0;
        num++;
        string IN_FID = ret_res.Rows[index]["IN_FID"].ToString();
        string strnum = num.ToString();
        NewList.Add(IN_FID);
        dic.Add(NEAR_FID, new List<string>(NewList));
        NewList.Clear();
    }
}

运行之后报错如下:

显示Object reference not set to an instance of an object(对象引用没有设置为一个对象的实例),list是null。这种情况出现的原因是因为List集合为null的时候相当于不存在,所以添加不了元素。用日常生活举例,当你找不到一个容器的时候,你怎么能往容器里装东西呢?有非常多的解决方法。我使用下面的方法解决:

Dictionary<int, List<string> >dic = new Dictionary<int, List<string>>();
int rowCount = ret_res.Rows.Count;
for (int index = 0; index < rowCount; index++)
{
    List<string> NewList = new List<string>();
    int NEAR_FID = Convert.ToInt32(ret_res.Rows[index]["NEAR_FID"]);
    if (dic.TryGetValue(NEAR_FID, out NewList))
    {
        List<string> tempList = new List<string>();
        tempList = dic[NEAR_FID];
        int tempnum = int.Parse(tempList.First());
        tempnum++;
        string IN_FID = ret_res.Rows[index]["IN_FID"].ToString();
        tempList[0] = tempnum.ToString();
        tempList.Add(IN_FID);
        dic[NEAR_FID] = tempList;
        //dic.Add(NEAR_FID, new List<string>(tempList));
        tempList.Clear();
    }
    else
    {
        int num = 0;
        num++;
        string IN_FID = ret_res.Rows[index]["IN_FID"].ToString();
        string strnum = num.ToString();
        var _list = new List<string>();
        _list.Add(strnum);
        NewList = _list;
        NewList.Add(IN_FID);
        dic.Add(NEAR_FID, new List<string>(NewList));
        NewList.Clear();
    }
}

大概思路是,我创建了类型相同的临时List集合,变量名为“_list”,用来添加字符串“strnum” ,然后再把添加完成的临时List集合“_list”赋值给为null的List集合“list”,这样就完成了为null的List集合的元素的添加。

 

posted @ 2022-09-02 12:27  Weltㅤ  阅读(429)  评论(0编辑  收藏  举报