Showing posts with label linq. Show all posts
Showing posts with label linq. Show all posts

Sunday, February 27, 2011

.NET Nugget : Viewing the serialized output of a DataContract on the console

Here are the steps (call it denotes sample variable names):
  • Create a DataContractSerializer of the type of the DataContract class (call it dcs)
  • Create a StringBuilder (call it sb)
  • Create an XmlWriter from the string builder ( call it writer)
  • use the dataContractSerializer.WriteObject to write the item instance to the xmlwriter. 
  • Print the sb.ToString to the console.

Heres the code: 

DataContractSerialzer dcs = new DataContractSerialzer(typeof(DataContractClass));
StringBuilder sb = new StringBuilder();
using(XmlWriter writer = new XmlWriter(sb))
{
   dcs.WriteObject(writer,dataContractClassInstance);
}
Console.WriteLine(sb.ToString());
Enjoy!

Monday, February 21, 2011

LINQ : Whats the purpose of AsEnumerable?

AsEnumerable has a funny method signature:


public static IEnumerable AsEnumerable(
 this IEnumerable source
)

But there is a good reason for this function to exist. The reason is that your collection might not be acually an IEnumerable and infact inherit from IEnumerable. In that case any extension methods (e.g. Where ) overridden in the class that inherits from IEnumerable will get called. Sometimes you just want to call the extension method as implemented for IEnumerable (i.e. LINQ to objects). In this case you can use the AsEnumerable extension method and then call the extension method and linq to objects kicks in instead of Linq2SQL / Linq2Entities etc. 




Sunday, February 20, 2011

.NET cool things

Some things I think everyone in .NET should know :)

Enjoy!

Saturday, February 19, 2011

LINQ syntax for left outer join

Hint : Use the DefaultIfEmpty() extension and the into contextual keyword

The trick is to store the result of the join into a collection and the select from the outer collection and the into 

e.g.:

var expr = from p in products 
               join o in customersOrders  
                    on p.IdProduct equals o.IdProduct
                    into orders
               
                    from order in orders.DefaultOrEmpty()
                         select new
                         {
                            p.IdProduct, 
                            Name = o.Name               
                         }


Notice that the only thing that makes it a left outer join is the use of into orders and then from using the orders.DefaultOrEmpty.

Ofcourse a right outer join is a left outer join with the collection orders swapped. 


Enjoy!

Friday, February 18, 2011

LINQ to objects : The impact of join order

Here's the sample syntax of the join clause:

var expr = from a in collectionA
           join b in collectionB
                on a.AKey equals b.BKey
           ...


Notes:

  • equals is a contextual keyword specifically for LINQ. 
  • In the on section the first rangeItem (a) Must come before the second rangeItem (b) . Otherwise the query will not compile. 
  • Internally for LINQ to objects the first collection is looped storing the hash for each Key. And then the second item is looped computing the hash and comparing it to the first item. So the output will contain order of the items in the first collection :)

Enjoy!



Thursday, February 17, 2011

LINQ : Notes about sorting

The Ascending Keyword:
The default order for the orderby keyword is ascending. So in actuality specifing ascending in a LINQ query is only there for explicit mentioning for the ease of the programmer and is ignored by the compiler.

In fact orderby translates into one of four possible extension methods by the compiler:


A bit more:
http://dotnetperls.com/ascending

The return type is IOrderedEnumerable
IOrderedEnumerable inherits from IEnumerable and the reason it exits is because of ThenBy and ThenByDescending . These extension method only function on IOrderedEnumberable.

These are called when you politely write such linq queries:

var expr = from c in customers 
                      orderby c.Name descending, c.City
                                   select new { c.Name, c.City };



the c.City sorting is actually added using ThenBy.

Also bet you didn't know Reverse
Although it has no corresponding LINQ query syntax and you need to use the Extension method. It simply reorders the first item to be last etc.

What is the algorithm used by LINQ for sorting?
LINQ to objects uses quicksort. You can verify this by opening up System.Linq.EnumerableSorter in reflector.
For any other implementation of LINQ it is up to the implementation (ofcourse) e.g LINQ2SQL it will get traslated to SQL order by and it will be up to SQL Server to carry out the sorting and pick a sorting algorithm.



Wednesday, February 16, 2011

LINQ Tutorial : SelectMany extension method

Here's another thing I did not know about LINQ that I found out from this book.
SelectMany is how LINQ internally translates a collection of a collection into a flat collection.

Say you have a class:

public class Customer
{
      public Order[] Orders;
} 


and you write the following LINQ:


var orders = from customer in Customers
             select customer.Orders;


Needless to say you get an IEnumerable<order[]>
However if you want an IEnumerable<order> you can do that in LINQ syntax simply as:

var orders = from customer in Customers
                  from order in customer.Orders
                       select order;



The compiler will actually translate it into a SelectMany call :
var orders = Customers.SelectMany(customer => customer.Orders);


Note:
In fact SelectMany will always be called when there is a from after the first from.



Tuesday, February 15, 2011

About LINQ : Degenerate Queries

Degeneration is a law of nature. No seriously. But that's not what we are talking about here. We are talking about degenerate queries.

Here is a sample of a degenerate query:
from foo in collection select foo


Its called degenerate because it seemingly adds no value to the code e.g.:

var items = from foo in collection select foo;
foreach (var item in items)
{
      //Do something
}

We could have easily done (hypothetically):

foreach (var item in collection)
{
      //Do something
}

But it is required when you use linq to SQL ( or LINQ to EF or LINQ to XML etc) because these implementations of LINQ actually override the Select extension method. It looks degenerate ... but it is required for the API to hook in for expression evaluation. 

"A query that simply returns a result equal to the original data source is called degenerate query expression" 

Enjoy!


Sunday, February 13, 2011

LINQ Tutorial : The from clause

I am currently preparing for exam 70-516. Reading Programming Microsoft LINQ in Microsoft .NET Framework 4 for it and loving it. Here is something new I learnt:

The syntax of from:
from rangeVariable in dataSource

Now if dataSource is a strongly typed collection (and these are the only ones I ever create) the rangeVariable will automatically be typed according to that.
e.g. if dataSource is IEnumerable , rangeVariable will be typed as T 

What I did not know
However if dataSource is ArrayList or any other untyped datasource you will need to specify the type in the syntax :
from T rangeVariable in untypedDataSource 


Cool eh.
Enjoy!