将对象列表添加到另一个列表C# [英] Add list of objects to another list C#
问题描述
我正在玩List<>对象我试图在列表中创建日期列表。基本上一个对象列表可以包含3个日期。
我不知道怎么做。
班级人物:
I am playing around with List<> of objects. I was trying to create a list of dates within a list. Basically an object list can contain i.e 3 dates.
Im not sure how to do it.
Class called people:
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public List<Dates> numberOfDates{ get; set; } = new List<Dates>();
类称为日期:
Class called Dates:
public DateTime date { get; set; }
我尝试过:
在我的主要表单中,我有两个事件处理程序。一个是 AddPerson 第二个是 AddDates 基本上当你添加日期时,我希望它保存到AddPerson按钮中以添加到对象中(如果有意义的话)。
What I have tried:
In my main form I have two event handlers. One is AddPerson second is AddDates Basically when you add dates I want it to save into the AddPerson button to added into the object (If that make sense).
private void AddPerson(object sender, EventArgs e)
{
Person person = new Person();
person.Name = txtFirstName.Text;
person.Surname = txtSurname.Text;
person.Age = int.Parse(txtAge.Text);
private void btnAddDates_Click_1(object sender, EventArgs e)
{
People people = new People();
Dates dates= new Dates();
dates.date = dtpClaim.Value; //dtp is the date time picker people.numberOfDates.Add(dates);
}
简而言之,我在addDates事件中添加日期/日期后,会将其添加到特定日期addPerson事件中的人。
In short, once I add a date/dates in the addDates event, it will add it to the specific person in the addPerson event.
推荐答案
您需要识别相应的人员实例 - 我不知道您如何存储它们,您没有表明:每次添加日期时都会重新创建Person实例,因此它不能存在。
但是一旦你拥有了Person,就很容易:
You need to identify the appropriate person instance - and I have no idea how you are storing them, you don't show that: the Person instance is created anew each time you add a a date, so it can't be there.
But once you have the Person, it's easy:
myPerson.numberOfDates.add(dates);
BTW:尽量避免将事物命名为复数,除非它们是一个集合:Dates是一个单日期存储对象,因此它应该是Date,而People应该是人 - 但你似乎也有一个班级......这让人感到困惑!
BTW: try to avoid naming things as plurals unless they are a collection: "Dates" is a single date storage object, so it should be "Date", and "People" should probably be "Person" - but you appear to have a class for that as well...which gets confusing!
这篇关于将对象列表添加到另一个列表C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!