Tuesday, December 21, 2010

LINQ Can Improve Your C# Programming

Introduction

LINQ has its own set of Query operators which make it powerful. These exist in the System.LinqSystem.Core assembly. These are extension methods on the Enumerable and Queryable objects. Namespace within the
The standard LINQ query operators can be classified into the following types:

Qualifiers Operators
Any, All, Contains
Set Operators
Distict, Union, Intersect, Except
Ordering Operators
OrderBy, OrderByDescending , ThenBy , ThenByDescending , Reverse
Equality Operators
SequenceEqual
Conversion Operators
Cast, ToArray, ToList, ToDictionary, OfType, SingeOrDefault
Grouping Operators
GroupBy
Joining operators
Join, GroupJoin
Element Operators
First, FirstOrDefault,ElementAt
Partitioning Operators
Take, Skip, TakeWhile, SkipWhile
Projection Operators
Select , SelectMany
Aggregate Operators
Count, Sum ,Min, Max, Average, Aggregate
Restriction Operators
Where
Concatenation operators
Concat
Generation Operators
Range, Repeat

This article will focus on a handful of LINQ queries that can improve our C# programming.

1.   Avoiding FOREACH on Collections to Filter for Data

You can avoid the FOREACH and the IF clauses inside your FOREACH to filter for data. Check the below sample that eliminates the confusing conditional statements with a simpler LINQ query.
LINQ CODE
 var filteredUsers = from currentUser in Users
                                where currentUser.Active && currentUser.AllowLogin&& ! urrentUser.LoggedIn
                                select user;

2.   Select X Rows

When we have to select a few rows from a collection, we check the loop counter with a fixed constant and break the for loop or control the loop counter.
               
LINQ CODE
 var filteredUsers = Users.Where(u => u.Active && u.AllowLogin && !u.LoggedIn)
                                                  .Take(10)

3.   Take the First Element from a Collection

We face lot of situations where we have to read the first element in a collection. We would start off by evaluating the collection with null and then its elements count and so on. Now, there is a possibility that this collection might be empty.

LINQ CODE
List<string> adminUsers = RetrieveUsersForAdminRole(RoleType.Admin);
  User firstUser = adminUsers.FirstOrDefault();
   If there are no users found, it returns the default value of the underlying type.

4.   Let Go the IComparer<T> for Sorting

We no more need to write the tough IComparer classes to sort our custom data. We can now use the OrderBy method to order the data. Look at the sample query below for more brevity.
LINQ CODE
var filteredUsers = Users.Where(u => u.Active && u.AllowLogin && !u.LoggedIn).OrderBy( u => u.Name);

The ORDERBY function takes in a parameter that is used to sort. If you want do a multi-sort , use the THENBY operator.
LINQ CODE
var filteredUsers = Users.Where(u => u.Active && u.AllowLogin && !u.LoggedIn).OrderBy( u => u.Name).ThenBy(u => u.Location);
  
Yes, you can sort in a Descending fashion too. LINQ provides the ORDERBYDESCENDING operator for this very purpose.

LINQ CODE
var filteredUsers = Users.Where(u => u.Active && u.AllowLogin && !u.LoggedIn).OrderByDescending( u => u.Name).ThenBy(u => u.Location);
                                 
Note: There is a ThenByDescending operator too.

5.   Do Not Use for Loops to Initialize Arrays

Do not use for loops to initialize arrays. We do this a lot of times to write quick test code. This can be replaced using the System.Linq.Enuemerable.Range method.
Using LinQ it is just one line of code.

LINQ CODE
 int[] monthsInAYearByLINQ = System.Linq.Enumerable.Range(1, 12).ToArray();
                 

6.   Replace Two Similar Loops with Concat

If you have to loop through two arrays which are similar in nature, you can use the Concat extension and write concise code. Now, consider this piece of code which uses the Concat operator.

LINQ CODE
int[] firstArray       = System.Linq.Enumerable.Range(1, 12).ToArray();
int[] secondArray = System.Linq.Enumerable.Range(13, 12).ToArray();
  
foreach (var a in firstArray.Concat(secondArray))
{
allElements.AppendLine(string.Format("{0}", a));
}
                 

7.   Avoid Transformations

A transformation is a technique that you follow to return a new collection that is obtained by looping through another collection and applying filters on them.
Instead of creating a temporary list and then filling it up with users, we can use the LINQ SELECT and the ToArray Method to return the results for us.
LINQ CODE
public Users[] FindUsers(RoleType r)
  {
      return FindUsers()
          .Select(user => new User
                          {
                                FirstName = u.FirstName,           
                                     …
                              });
                 .Where(user => user.Role == r)
          .ToArray();
  }

8.   The Let Keyword

The LET keyword lets you build temporary variables in your LINQ query, so that your SELECT query becomes easier to read, and maintain. It lets you predefine variables at a certain stage of the query that can be used in the rest of the query.
For example, the following query calculates the average twice. This can be replaced by using the LET operator. The query will perform faster as the Average is not calculated twice.
LINQ CODE(Simple Query)
var results= from store in Stores where store.Sales.Average(s => s.Price) > 500
select new
{
Name = store.Name
StoreAveragePrice = store. Sales.Average(s => s.Price)
 };

See the following snippet that uses the LET keyword.
LINQ CODE(Query using Let)
var results= from store in Stores
let AveragePrice =  store.Sales.Average(s => s.Price)
 where AveragePrice > 500
select new
 {
Name = store.Name
StoreAveragePrice = AveragePrice
 };
                 

9.   RegEx + LINQ?

LINQ queries can help you work with Regular Expression results and make your henceforth queries simpler. Look at the following sample that iterates over a collection iterating them over the regex expression.
Note that you can do other LINQ queries on the RegEx Matched results.

LINQ CODE
List<string> examinerStatements = new List<string>();
examinerStatements.Add("Mark was present.");
examinerStatements.Add("Julie was present.");
examinerStatements.Add("John was absent");
 
System.Text.RegularExpressions.Regex myRegEx = new System.Text.RegularExpressions.Regex("present");
 
var presentStudents = examinerStatements
.Where<string>(statement => myRegEx.IsMatch(statement))
.ToList<string>();
 
foreach (var examinerStatement in presentStudents)
{
       //
}
                 

10. Querying ArrayList

You would have found that you cannot run LINQ queries on an ArrayList. That is because it does not implement the System.Collections.Generic.IEnumerable<T> interface.

LINQ CODE
List<string ArrayList myList = new ArrayList();
                                myList.Add("One");
                                myList.Add("Two");
                                myList.Add("Three");
                    
var results = from value in myList select new { value };
                 
You can use the Cast Operator in such cases. The modified code snippet below shows you how to use that.

LINQ CODE
ArrayList myList = new ArrayList();
              myList.Add("One");
              myList.Add("Two");
              myList.Add("Three");
var results = from value in myList.Cast<string>()   select new { value };
                 
  I hope these ten samples helped you learn something new and enjoy reading.

References

Related Articles


No comments:

Post a Comment