Thursday, May 17, 2007

* C# 3.0 New Features : All LINQ(K)ED in one

In my previous post i attended the summary of new csharp 3.0 features.

Although all the new CSharp 3.0  can be used independently of LINQ but it seems most of them have been introduced to support LINQ and make it simpler.

Here is LINQ sample which demonstrates the use of most important of them :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AllCsharp3
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> words = new List<string> { "Word1", "World", "Word2", "Word3", "World4" }; //Collection Initializer
            var wordQuery =  // Implicitly Typed Local Variables
            from word in words
            where word == "World"
            select new{word};  //Anonymous Types
            foreach (var name in wordQuery)
            {
                Console.WriteLine("-> Hello " + name.word);
                Console.WriteLine("-> Hello " + name.word.ToString().GetFirst3Chars());
            }
        }
    }

    public static class MyExtensions  
    {
        public static string GetFirst3Chars(this System.String str)  //Extension Methods
        {
            return str.Substring(0, 3);
        }
    }
}

Other Posts

No comments:

Post a Comment