This blog is moved to
http://amalhashim.wordpress.com

Thursday, November 12, 2009

Basic usage of LINQ

We can use LINQ in any scenario where we want to iterate through a list of items. For example how about listing all types in the current application domain?

var asm = from a in AppDomain.CurrentDomain.GetAssemblies()
from type in a.GetExportedTypes()
select type;

foreach (var val in asm)
{
Console.WriteLine(val.Name);
}

How about listing all 3.5 assemblies order by length

var alist = asm.Where(x => x.Assembly.FullName.Contains("3.5.0.0")).
OrderByDescending(x => x.Name.Length);

foreach (var val in alist)
{
Console.WriteLine(val.Name);
}

Lets find the total count of types for each version

var vers = asm.Select(
x => x.Assembly.FullName.Split(",".ToCharArray())[1])
.GroupBy(y => y)
.Select(z => new { VerName = z.Key, Count = z.Count() });

foreach (var ver in vers)
{
Console.WriteLine(".NET {0} has {1} types\n", ver.VerName, ver.Count);
}
Interesting right?

No comments: