C#中如何将数据添加到Collection列表中
How to add data into Collection list in c#
我正在尝试从 SQL 数据库中获取数据,我得到了 5 条记录。但是我想从那 5 个记录列表中分别创建两个列表。我正在尝试执行以下操作:
public class ParentModel
{
public List<Model1> Child1 { get; set; }
public List<Model2> Chil2{ get; set; }
}
我的另外两个模型是:
public class Model1
{
public int Id { get; set; }
public string Name { get; set; }
public int? GroupNumber { get; set; }
public string Description { get; set; }
}
public class Model2
{
public string Name { get; set; }
public int? Number { get; set; }
}
我想填充 ParentModel 中定义的两个列表
我的服务,但它抛出空异常。如何将数据添加到我的列表中?
public ParentModel GetALL(int ID)
{
ParentModel objModel = new ParentModel();
// here I fetch data from database using Iqueryable:
IQueryable<Products> List = this._products.GetAll();
var NamesList = List .Where(m => m.Id == ID).ToList();
// Here I need to add data to my list. Also if it can be
// followed in a best possible way, Please do share it with me.
foreach (var obj in NamesList)
{
objModel.Child1.Add( new Model1
{
Id=obj.Id, // Here it throws error of null exception
Name = obj.Name,
GroupNumber = obj.GroupNumber,
Description =obj.Description
});
// the other list I would like to populate at the same time is
objModel.Chil2.Add(new Model2
{
Name = obj.Name,
Number = obj.Number
});
}
}
有几种方法。最简单的方法是添加构造函数
public class ParentModel
{
public List<Model1> Child1 { get; set; }
public List<Model2> Chil2 { get; set; }
public ParentModel()
{
Child1 = new List<Model1>();
Chil2 = new List<Model2>();
}
}
我正在尝试从 SQL 数据库中获取数据,我得到了 5 条记录。但是我想从那 5 个记录列表中分别创建两个列表。我正在尝试执行以下操作:
public class ParentModel
{
public List<Model1> Child1 { get; set; }
public List<Model2> Chil2{ get; set; }
}
我的另外两个模型是:
public class Model1
{
public int Id { get; set; }
public string Name { get; set; }
public int? GroupNumber { get; set; }
public string Description { get; set; }
}
public class Model2
{
public string Name { get; set; }
public int? Number { get; set; }
}
我想填充 ParentModel 中定义的两个列表 我的服务,但它抛出空异常。如何将数据添加到我的列表中?
public ParentModel GetALL(int ID)
{
ParentModel objModel = new ParentModel();
// here I fetch data from database using Iqueryable:
IQueryable<Products> List = this._products.GetAll();
var NamesList = List .Where(m => m.Id == ID).ToList();
// Here I need to add data to my list. Also if it can be
// followed in a best possible way, Please do share it with me.
foreach (var obj in NamesList)
{
objModel.Child1.Add( new Model1
{
Id=obj.Id, // Here it throws error of null exception
Name = obj.Name,
GroupNumber = obj.GroupNumber,
Description =obj.Description
});
// the other list I would like to populate at the same time is
objModel.Chil2.Add(new Model2
{
Name = obj.Name,
Number = obj.Number
});
}
}
有几种方法。最简单的方法是添加构造函数
public class ParentModel
{
public List<Model1> Child1 { get; set; }
public List<Model2> Chil2 { get; set; }
public ParentModel()
{
Child1 = new List<Model1>();
Chil2 = new List<Model2>();
}
}