Tuesday, March 11, 2014

Mulitple "from" statement in LINQ and a Single Element Sequence example

I like to use multiple "from" statement in my LINQ query for two reasons:
1. It's easy to understand. It maps naturally to a nested loop like the following
   
    foreach(var outerElement in outSequence.Where(t => ...)) 
  {
     // outerElement can be used in the inner query
           foreach(var innerElement in outSequence.Where(t => ...))
    {
        ....
    }
  }

2. It is more flexible than "join" because there is not limit on how you use the outer element in inner query. As shown by the following example. 

Sometimes, you may want to select a single element sequence in LINQ. For example, once I needed to use several from statements and some from statement should return a single element sequence. In LINQ, it is pretty easy with a multiple from query:

from outerElement in outSequence
  .Where(t => ...)
from innnerElement in innerSequence
  .Where(t => ...)
  .DefaultIfEmpty()
  .Take(1);

The second "from" statement returns exactly one element sequence result. In the above example, the number of element of the above query result is the number of element returned from the first query.

No comments:

Post a Comment