Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建列表<;对象>;在C中#_C#_List_Class - Fatal编程技术网

C# 创建列表<;对象>;在C中#

C# 创建列表<;对象>;在C中#,c#,list,class,C#,List,Class,我正在尝试创建一个类似这样的类: 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)

我正在尝试创建一个类似这样的类:

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;
        }
    }
公共类个人列表:列表
{
公众人物列表()
{ 
}
public int getAge(字符串名称)
{ 
foreach(字符串s n this)
{
如果(s==名称)
回归年龄;
}
}
我的目标是使用名为GetAge()的简单函数,以便根据列表中任何person对象的名称获取年龄。 我知道只创建一个列表是可能的,但我想要一个模块化代码

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;       
}

<>我想你必须考虑一个<强>名称可以在列表< /强>中重复,所以你可以任意地得到第一个,在下面的示例中你有两个选项。
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();
        }
    }

你有什么问题吗?代码似乎还可以,你到底想做什么?getAge中的循环不能作为字符串迭代。列表中的类型不是字符串,而是人物。有更简单/更优雅的方法可以使用linq获取列表项的属性
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();
        }