-4

我想使用 LINQ 将数据放入类中。

类人

public class Person
{
    public int Id {get; set;}
    public string Name { get; set; }
    public List<string> Surname { get; set; }
}

我想添加 2 个人,然后找到 id 为 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?
4

2 回答 2

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);
于 2013-05-16T19:09:04.117 回答
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();
于 2013-05-16T19:10:13.283 回答