gpt4 book ai didi

c# - 从 C# 中的对象数组中获取最大值

转载 作者:行者123 更新时间:2023-11-30 19:43:04 27 4
gpt4 key购买 nike

我有一个包含对象的数组,这些对象有一个字符串、一个整数和一个字符属性。

Person[] people = new Person[1]; //Declare the array of objects

[...] This code is irrelevant

Person person = new Person(name, age, gender); //This creates instance a new object
people.SetValue(person, i); //is just a variable which increase in a c
Array.Resize(ref people, people.Length + 1); //Change array size
i++; // Autoincrement

[...] 更多代码来填充有效的值

我想从 people 数组中存储的所有对象 person 中获取该人的年龄最大值(age 属性为整数值)

最佳答案

最简单的方法是使用 LINQ:

using System.Linq;

var maxVal = people.Max(x => x.Age); // get highest age
var person = people.First(x => x.Age == maxVal); // get someone with such an age

关于c# - 从 C# 中的对象数组中获取最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16094183/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com