提问者:小点点

筛选对象数组以移除属性中没有最大值的对象


我如何过滤对象数组,以移除那些没有最大年龄值的对象。

namespace app1
{
    class Program
    {
        static void Main(string[] args)
        {

            Container[] containers = buildContainers();

            // how can I get an array of containers that only contains the IMCB with the greatest Age.
            // eg: [ {IMCB = "123456", Age = 3, Name = "third"}, {IMCB = "12345", Age = 4, Name = "fourth"}  ]

        }

        static Container[] buildContainers()
        {

            List<Container> containers = new List<Container>();
            containers.Add(new Container() { IMCB = "123456", Age = 1, Name = "first" });
            containers.Add(new Container() { IMCB = "123456", Age = 3, Name = "third" });
            containers.Add(new Container() { IMCB = "12345", Age = 2, Name = "second" });
            containers.Add(new Container() { IMCB = "123456", Age = 2, Name = "second" });
            containers.Add(new Container() { IMCB = "12345", Age = 4, Name = "fourth" });
            return containers.ToArray();
        }


    }

    class Container
    {
        public string Name { get; set; }
        public string IMCB { get; set; }

        public int Age { get; set; }
    }

}

共1个答案

匿名用户

首先,弄清楚什么是最伟大的时代:

var maxAge = containers.Max( x => x.Age );

然后选择不匹配项:

var result = containers.Where( x => x.Age < maxAge );