LINQ und C#3

LINQ = language integrated query: typsichere Verarbeitung von Daten aus

Wesentliche programmiersprachliche Neuerungen:

Beispiel:

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication4
{
    class Student
    {
        public string name;
        public string vorname;
        public int id;
    }

    static class Program
    {
	// Erweiterungsmethode ( extension method )
        static string Form (this Student s){
            return s.vorname + s.name;
        }


        static void Main(string[] args)
        {

            int x = 4;
            var y = x * x; // Typinferenz
            Console.WriteLine(y);


            string[] cities = { "leipzig", "paris", "athen" , "london" };
            // embedded SQL
            IEnumerable<string> result1
                = from c in cities
                  where c.StartsWith ("l")
                  orderby c.Length
                  select c;
            // Übersetzung in Methodenaufrufe
            foreach 
                (string stadt in 
                cities
                .Where(c => c.StartsWith("l"))
                .OrderBy(c => c.Length)
                )
                
            {
                Console.WriteLine(stadt);
            }



            Student[] sg =
            { new Student ()  { id=3, name = "foo", vorname = "bar" }
              };

            // Erweiterungsmethode benutzen
            Console.WriteLine(sg[0].Form());

            // anonyme Klasse (als Resultattyp)
            var result2
                = from s in sg
                  select new { id = s.id, name = s.name };

            foreach (var s in result2)
            {
                Console.WriteLine(s);
            }
            Console.ReadLine();
        }
    }
}

Literatur:



Johannes Waldmann 2007-06-21