Link to home
Start Free TrialLog in
Avatar of weimha
weimhaFlag for United States of America

asked on

Using Linq to filter collection with group By and select max

Given the sample code shown below, how can I use linq to filter the collection to group By field1 and select the highest value of field2, so that my new collection would have classB and classC only in it?
public class Class1
    {
        public int field1;
        public int field2;
        public DateTime field3;
        public int field4;
    }
 
    public class Class1Collection : Collection<Class1>, IEnumerable<Class1>
    {
    }
 
 
    public static class TestClass
    {
 
        public static void Test()
        {
            Class1 classA = new Class1();
            classA.field1 = 1;
            classA.field2 = 2;
            classA.field3 = new DateTime(2009, 01, 01);
            classA.field4 = 3;
 
            Class1 classB = new Class1();
            classB.field1 = 1;
            classB.field2 = 3;
            classB.field3 = new DateTime(2009, 02, 01);
            classB.field4 = 3;
 
            Class1 classC = new Class1();
            classC.field1 = 2;
            classC.field2 = 1;
            classC.field3 = new DateTime(2009, 02, 01);
            classC.field4 = 3;
 
            Class1Collection collection = new Class1Collection();
            collection.Add(classA);
            collection.Add(classB);
            collection.Add(classC);
 
            Class1Collection filteredCollection = ??
        }
 
    }

Open in new window

SOLUTION
Avatar of Craig Wagner
Craig Wagner
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial