How can I add multiple records by using same class properties? My added latest record overwritten previous one.
[HttpGet]
public ActionResult Questions()
{
RecommendModel recommendmodel RecommendModel();//My Model/class File
List<RecommendModel>recommends = new List<RecommendModel>();//GenericList
recommendmodel.ID=55;
recommendmodel.Name = "First";
recommends.Add(recommendmodel);
recommendmodel.ID=56;
recommendmodel.Name = "Second";
recommends.Add(recommendmodel);
var list = recommends; //Return count two but overwriting first value .
}
My List overwritten first added value. How can i add multiple records by using same class properties. What I am doing wrong here?
CodePudding user response:
You are not creating new object of RecommendModel.
List<RecommendModel>recommends = new List<RecommendModel >(); //GenericList
RecommendModel recommendmodel = new RecommendModel(); //My Model/class File
recommendmodel.ID=55;
recommendmodel.Name = "First";
recommends.Add(recommendmodel);
recommendmodel = new RecommendModel(); You need to create a new Object Here
recommendmodel.ID=56;
recommendmodel.Name = "Second";
recommends.Add(recommendmodel );
CodePudding user response:
You have only one instance of type RecommendModel
and thus the values are overwritten by the second assignment.
Try this instead:
[HttpGet]
public ActionResult Questions()
{
var recommendmodel1 = new RecommendModel()
{
ID = 55,
Name = "First"
};
var recommendmodel2 = new RecommendModel()
{
ID = 56,
Name = "Second"
};
var list = new List<RecommendModel>()
{
recommendmodel1,
recommendmodel2
};
//-- And so on ...
}
CodePudding user response:
When you are adding a recommendmodel
you are not inserting a new object. What happens is that a reference to the recommendmodel
gets added.
Later in your flow you are updating that object, thus changing the object. Your reference in your list is still to this object. What you want to do is create a new object and insert that into your list.
List<RecommendModel>recommends = new List<RecommendModel >();
var firstRecommendmodel = new RecommendModel()
{
ID = 55,
Name = "First"
};
recommends.Add(firstRecommendmodel);
var secondRecommendmodel = new RecommendModel()
{
ID = 56,
Name = "Second"
};
recommends.Add(secondRecommendmodel);
var list = recommends;