Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/317.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#_List_Object_Compare - Fatal编程技术网

C# 比较同一列表中对象的值

C# 比较同一列表中对象的值,c#,list,object,compare,C#,List,Object,Compare,我搜索了这个主题,但它总是显示两个需要比较的列表的结果 如何比较同一列表中两个或多个对象的特定属性 例如,在下面的示例代码中,我如何仅比较年龄值来找出整个列表中哪个人是最年轻的?谢谢 public class Person { private string name; private short age; public Person(string name, short age) { this.name = name;

我搜索了这个主题,但它总是显示两个需要比较的列表的结果

如何比较同一列表中两个或多个对象的特定属性

例如,在下面的示例代码中,我如何仅比较年龄值来找出整个列表中哪个人是最年轻的?谢谢

public class Person
{
    private string name;
    private short age;


     public Person(string name, short age)
     {
         this.name = name;
         this.age = age;
     }

     public string Name
     {
         get { return name;  }
         set { name = value; }
     }

     public short Age
     {
         get { return age; }
         set { age = value; }
     }

}

List<Person> PersonList = new List<Person>();

PersonList.Add(new Person("John Smith", 35));
PersonList.Add(new Person("Jane Doe", 18));
PersonList.Add(new Person("Bill Lee", 28));
公共类人物
{
私有字符串名称;
私人短龄;
公众人物(字符串名称,短年龄)
{
this.name=名称;
这个。年龄=年龄;
}
公共字符串名
{
获取{返回名称;}
设置{name=value;}
}
公众短龄
{
获取{返回年龄;}
设置{age=value;}
}
}
List PersonList=新列表();
添加(新人物(“约翰·史密斯”,35));
PersonList.Add(新人物(“Jane Doe”,18));
添加(新人物(“Bill Lee”,28));

根据
年龄
属性排序并返回第一个元素:

Person the_youngest = PersonList.OrderBy(i => i.Age).ToList<Person>().First();
Person the_mineet=PersonList.OrderBy(i=>i.Age.ToList().First();
还可以使用Linq进行就地排序:

PersonList = PersonList.OrderBy(x => x.Age).ToList<Person>();
PersonList=PersonList.OrderBy(x=>x.Age.ToList();

您尝试过linq表达式吗?
var mineest=PersonList.OrderBy(x=>x.Age).FirstOrDefault()
对于少量项目,这是可以接受的简单方法,但是对于较大的项目,这会对整个列表进行排序,而不是简单地扫描最大的成员,这会占用更多的CPU和RAM。