我想使用LINQ将数据放入类中。
班级人员
public class Person
{
public int Id {get; set;}
public string Name { get; set; }
public List<string> Surname { get; set; }
}
我想添加2个人,然后找到身份1的人,然后编辑姓名。你知道怎么做吗?
public List<Person> persons { get; set; }
public void example()
{
persons = new List<Person>();
}
类似的东西?
new List<Person>{
Id = 1,
Name = "sadsad",
Surname = new string Suname {Surname="Examle"}
};
persons = (from a in Person
where a.Id = 1
select a).FirstOrDefault<Ankieta>();
string s = persons.Name; // Update?
答案 0 :(得分:2)
增加2人
List<Person> persons = new List<Person>{
new Person(){
Id = 1,
Name = "sadsad",
Surname = new List<string>(){"Examle"}
},
new Person(){
Id = 2,
Name = "fbs",
Surname = new List<string>(){"ggg"}
}};
// adding another person
persons.Add(new Person() { Id = 3, Name = "cc", Surname = new List<string>() { "ggg" } });
找到ID为1的人,然后使用ForEach
persons.ForEach(p => p.Name = (p.Id == 1) ? "NewName" : p.Name);
答案 1 :(得分:2)
首先,我将姓氏键入string
:
public class Person
{
public int Id {get; set;}
public string Name { get; set; }
public string Surname { get; set; }
}
然后:
persons.Add(new Person(){ Id = 1, Name = "Name", Surname = "Surname" });
//...
var result = (from a in persons where a.Id == 1 select a).FirstOrDefault();