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

时间:2013-04-18 22:33:52

标签: c#

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

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

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

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

6 个答案:

答案 0 :(得分:5)

最简单的方法是使用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

答案 1 :(得分:1)

如果要在每次添加新项目时调整大小,都不应该使用数组。这就是泛型List类的用途。你可以写:

List<Person> People = new List<Person>();
Person person = new Person(name, age, gender);
People.Add(person);

List负责在需要时调整后备阵列的大小。每次添加项目时,它都比调整数组大小更容易,更有效。

要获得最大年龄,您可以使用其他答案中显示的LINQ表达式之一。如果您想要具有最大值的记录,则必须遍历列表:

Person maxItem = People[0];
foreach (Person person in People)
{
    if (person.Age > maxItem.Age)
    {
        maxItem = person;
    }
}

答案 2 :(得分:0)

我假设您的Person类看起来像这样: -

class Person
{
  public int Age { get; private set; }
  public string Name { get; private set; }
  public string Gender { get; private set; }

  // constructor etc
}

<强>改进

如果你有一个Person的可枚举,即'人',我建议你使用一个带有IList等接口的容器,即: -

IList<Person> people = new List<Person>();

这样可以避免手动调整阵列大小。

<强>解决方案

要获得最大的年龄,你可以做一些事情: -

var max = people.Max(p => p.Age);

进一步阅读

这是一个Linq查询;更多信息可以在这里找到: -

http://msdn.microsoft.com/en-gb/library/vstudio/bb397926.aspx

你可以用linq做很多“很酷”的事情,例如选择一个可以忽略的年龄,即

var ages = people.Select(p => p.Age);

这将返回一个包含列表中每个人年龄的可枚举项。如果你想要所有超过一定年龄的人,你可以使用Where,即: -

var above = people.Where(p => p.Age > 65);

答案 3 :(得分:0)

我完全同意@dlev留下的评论,因为您不应该使用传统的Arrays,而是使用List<T>来自动处理您的收藏品的大小调整。

此外,因为ArrayList<T>都实现了IEnumerable,您可以使用LINQ来操作元素,实际上请查看可用的whole list of methods。< / p>

适用于您的方案的具体示例:

var maxVal = people.Max(x => x.Age);
var person = people.First(x => x.Age == maxVal);

答案 4 :(得分:0)

这样的事情对你有用:

Person[] persons = {};
Person oldest = persons.Aggregate( (x,y) => x.Age > y.Age ? x : y ) ;

或者滚动你自己:

static T FindMax<T>( this IEnumerable<T> items , Func<T,T,int> comparer  ) where T:class
{
  T max = null ;
  foreach ( T item in items )
  {
    if ( item == null ) { continue ; }
    if ( max == null ) { max = item ; continue ; }

    // check current item against max.
    // if current item is "greater than" the current max
    // replace it.
    int cc = comparer(item,max) ;
    if ( cc > 0 )
    {
      max = item ;
    }
  }
  return max ;
}

用法:

Person[] persons = LoadPersons() ;
Person oldest = persons.FindMax<Person>( (x,y) => x.Age < y.Age ? -1 : x.Age > y.Age ? +1 : 0 ) ;

答案 5 :(得分:0)

如果列表相对较小(少于1000个对象),上面建议的内容将起作用。这是因为所有上述方法都使用顺序搜索。出于性能目的(速度),应用qsort方法更有效。例如:

class PersonAgeComparer : IComparer<Person>
{
    public Int32 Compare(Person x, Person y)
    {                
        if (x.Age > y.Age) return 1;
        if (x.Age < y.Age) return -1;

        return 0; // must be equal
    }
}

class Person
{
    public Int32 Age { get; set; }
}

static void Run1()
{
    Random rnd = new Random((Int32)DateTime.Now.Ticks);

    List<Person> persons = new List<Person>();
    for (Int32 i = 0; i < 100000; i++)
    {
        persons.Add(new Person() { Age = rnd.Next(100) });
    }

    persons.Sort(new PersonAgeComparer());

    // The oldest but you may have dups (same age)
    Person oldest = persons[persons.Count - 1];

}