2017-09-13 59 views
-3

我想创建这样一个类:在C#创建列表<objects>

public class person 
{ 
    public string name { get; set;} 
    public int age { get; set;} 
} 

,并创建一个类基本上是上述类的列表:

public class PersonList : List<person> 
{ 
    public PersonList() 
    { 
    } 

    public int getAge(string name) 
    { 
     foreach(string s n this) 
     { 
      if (s == name) 
       return age; 
     } 
    } 

我的目标是有简单的功能,名为GetAge()所以我通过任何我的名单中的对象的名称得到年龄。 我知道可以创建一个列表,但我想要一个模块化代码。

+6

那你有什么问题的控制台代码?代码似乎没问题,应该可以工作 –

+1

你想要做什么? –

+2

getAge中的循环不能迭代为字符串。列表中的类型不是一个字符串,它的人。 – Jay

回答

2
public int getAge(string name) 
{ 
    return this.First(x=>x.name==name).age;  
} 

如果找不到人员,这会引发错误。

返回-1时人未发现:

public int getAge(string name) 
{ 
    return this.FirstOrDefault(x=>x.name==name)?.age??-1;  
} 
0

我想你一定认为这是一个名称可以在列表重复,所以你任意会得到第一位的,在样品中下面你有两个选择。

public class person 
    { 
     public string name { get; set; } 
     public int age { get; set; } 
    } 
    public class PersonList : List<person> 
    { 
     public int getAge(string name) 
     { 
      return this.FirstOrDefault(x => x.name == name)?.age ?? -1; 
     } 
     public int[] getAge2(string name) 
     { 
      return this.Where(x => x.name == name).Select(x=>x.age).ToArray(); 
     } 
    } 

,你会得到的情况下,该名称重复年龄的列表,下面

static void Main(string[] args) 
     { 
      PersonList listOfPerson = new PersonList(); 
      listOfPerson.Add(new person() { age = 25, name = "jhon" }); 
      listOfPerson.Add(new person() { age = 26, name = "jhon" }); 
      listOfPerson.Add(new person() { age = 21, name = "homer" }); 
      listOfPerson.Add(new person() { age = 22, name = "bill" }); 
      listOfPerson.Add(new person() { age = 27, name = "jhon" }); 
      listOfPerson.Add(new person() { age = 22, name = "andrew" }); 

      foreach (var item in listOfPerson.getAge2("jhond")) 
      { 
       Console.WriteLine(item); 
      } 
      Console.ReadLine(); 
     }