03 July 2008 .NET 3.5, =>, C#3.0, HowTo, Lambda, List oliver.guhr

Seit der .Net Version 3.5 gibt es für Listen und Arrays eine Reihe neuer Funktionen um die Objekte zu durchsuchen, zu sortieren und zu ordnen. Um ein "Gefühl" für die neuen Funktionen zu bekommen habe ich eine kleine Demoanwendung geschrieben um ein Paar dieser neuen Funktionen auszuprobieren.

Grundlegende Informationen zu den Lambda Ausdrücken finden man hier: http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx 

http://www.outofcoffeeexception.de/2008/04/28/LambdaAusdruumlcke+In+C+30.aspx

            List<Person> Employees = PersonManager.GetRandomData(19);            
            
            Console.WriteLine("shows all employees");          
            ViewPersonList(Employees);
            
            Console.ReadLine();
            Console.Clear();
            Console.WriteLine("shows all Liza's (Where)");           
            ViewPersonList(Employees.Where(x => x.Firstname == "Liza").ToList());

            Console.ReadLine();
            Console.Clear();
            Console.WriteLine("order's all employees by PersonalId (OrderBy)");            
            ViewPersonList(Employees.OrderBy(x => x.PersonalId).ToList());
            
            
            Console.ReadLine();
            Console.Clear();
            Console.WriteLine("order's all employees by surename and firstname (OrderBy)");
            ViewPersonList(Employees.OrderBy(x => x.Surname).ThenBy(x => x.Firstname).ToList());

            Console.ReadLine();
            Console.Clear();
            Console.WriteLine("employee statistics (Min,Max,Sum,Average)");
            Console.WriteLine("the youngest employee is:\t" + Employees.Min(x => x.Age) + "\tyears old");
            Console.WriteLine("the oldest employee is:\t\t" + Employees.Max(x => x.Age) + "\tyears old");
            Console.WriteLine("all employee's are:\t\t" + Employees.Sum(x => x.Age) + "\tyears old");
            Console.WriteLine("the average age is:\t\t" + Employees.Average(x => x.Age));

            
            Console.ReadLine();
            Console.Clear();
            Console.WriteLine("groups's all employees by age(GroupBy)");
            Console.WriteLine("order's all groups by age(OrderBy)");
            Console.WriteLine("order's all employees in group's by surename(OrderBy)");
            IEnumerable<IGrouping<int, Person>> query = Employees.GroupBy(x => x.Age);
            foreach (IGrouping<int, Person> AgeGroup in query.OrderBy(x => x.Key ))
            {
                Console.WriteLine("----------Age:" + AgeGroup.Key + "------------------");
                ViewPersonList(AgeGroup.ToList().OrderBy(x => x.Surname).ToList());
            }
            Console.ReadLine();


Den Beispielcode gibts hier.