10 Ways LINQ Can Improve Your C# Programming

Introduction

MSDN describes it as "A query syntax that defines a set of query operators that allow traversal, filter and projection operations to be expressed in a direct, declarative way in any .NET framework-based programming language."

It allows you to query with a strongly typed syntax. LINQ has its own set of Query operators which make it powerful. These exist in the System.Linq Namespace within the System.Core assembly. These are extension methods on the Enumerable and Queryable objects. Below is a table highlighting them. The standard LINQ query operators can be classified into the following types:

The standard LINQ query operators
Figure 1

There are good numbers of websites that explain these operators with sufficient source code. MSDN, MSDN Magazine, 4guysfromrolla are few of them. This article will focus on a handful of LINQ queries that can improve our C# programming.

LINQ makes the intent of the code more obvious and helps your fellow developers to quickly adapt and work on your code and this is obviously the step after the inline documentation.

  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.

           CLASSIC CODE
       	 Users filteredUsers = new Users();
       	 foreach (User currentUser in Users)
       	 {
       	      If(currentUser.Active && currentUser.Enabled)
       	      {
       		If(!currentUser.LoggedIn)
       		  filteredUsers.Add(currentUser);
                               }
       	 }
       
        LINQ CODE
                        var filteredUsers = from currentUser in Users
                    		       where currentUser.Active && currentUser.AllowLogin&& ! currentUser.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.

    	                        CLASSIC CODE
    	   	 Users filteredUsers = new Users();
    	   	 for(int counter=0; counter < Users.Count; counter++)
    	   	{
    	   	      If(Users[counter].Active && Users[counter].Enabled)
    	   	      {
    	   		If(!Users[counter].LoggedIn)
    	   		  filteredUsers.Add(Users[counter]);
    	                    }
    	   		
    	                   If (filteredUsers.Count == 10)
    	   	    break;
    	   	 }
           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. So our classic code would look like:

      List<string> adminUsers = RetrieveUsersForAdminRole(RoleType.Admin);
      User firstUser = null;
      If (adminUsers != null) && (adminUsers.Count > 0)
      {
      	firstUser = adminUsers[0];
      }
    

    This can be replaced with a simple LINQ Query.

      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.

    	 		    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.

    	 		    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.

    	 		    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.

                int[] monthsInAYear = new int[12];
               for (int counter = 0; counter < monthsInAYear.Length; counter++)
              {
                       monthsInAYear[counter] = counter + 1;
              }
     

    Using LinQ it is just one line of 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. See the following example.

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

    Now, consider this piece of code which uses the Concat operator.

                   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. For example, refer the sample below. It creates a new Array after looping through a collection.

      public Users[] FindUsers(RoleType r)
      {
          IEnumerable<Users> users = FindUsers();
          List<Users> filteredUsers = new List<Users>();
      
          foreach (User u in users)
          {
      	if(u.Role == r)
      	{
              	filteredUsers.Add(new User
                                  {
      		FirstName = u.FirstName,	
      	                    …
                                  });}
          }
      
          return filteredUsers.ToArray();
      }
    

    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.

      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.

    			   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.

    			   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.

      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.

    	   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.

      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

    LINQ: .NET Language-Integrated Query
    101 LINQ Samples
    Link Cheat Sheet

    Related Articles





About the Author

Srinath M S

I would love to leave a footprint in this flat world

Comments

  • Whitened Mother of Pearl Dial using Diamonds Watch.

    Posted by Ricsninny on 06/19/2013 12:15am

    レディースウォッチ異なるデ [url=http://www.watchjpyoi.com/]カシオ 腕時計[/url] ザイン。インクルードまた、構成 [url=http://www.watchjpyoi.com/]シチズン 腕時計[/url] されています包含もなどを含む [url=http://www.watchjpyoi.com/]グッチ 時計[/url] 同じ多機能メンズ腕時 [url=http://www.watchjpyoi.com/]www.watchjpyoi.com/[/url] シチズン 腕時計 計を。これらの時計は、 [url=http://www.oakleburanndo.com/]オークリー サングラス[/url] さらにもなる銀メッキま [url=http://www.oakleburanndo.com/]オークリー ゴーグル[/url] たは金メッキ、それを作る活気望 [url=http://www.oakleburanndo.com/]オークリー レンズ[/url] ましいすべてへのいずれ [url=http://www.oakleburanndo.com/]www.oakleburanndo.com/[/url] オークリー ゴーグル かまたはすべてにすべてま [url=http://www.seikowatchannka.com/]セイコー 腕時計[/url] たはいずれかへ。 Oneフェミニンスタ [url=http://www.seikowatchannka.com/]セイコー 時計[/url] イルカシオの時計はになります有 [url=http://www.seikowatchannka.com/]seiko 腕時計[/url] 名なカシオWaveseptor時計。時 [url=http://www.seikowatchannka.com/]www.seikowatchannka.com/[/url] セイコー 時計 計の次のカテゴリがは [url=http://www.watchkeiya.com/]シチズン 時計[/url] カシオの高級時計順序。 ものこれら [url=http://www.watchkeiya.com/]セイコー 腕時計[/url] は最も高価です。非常に一般 [url=http://www.watchkeiya.com/]カシオ 腕時計[/url] 的な例カシオス [url=http://www.watchkeiya.com/]www.watchkeiya.com/[/url] カシオ 腕時計 トリートライダーです [url=http://www.poloralphlaurenya.com/]ラルフローレン[/url] つまりの最高の仲間するためのものジ [url=http://www.poloralphlaurenya.com/]ポロラルフローレン[/url] ョギングやスポーツマンに [url=http://www.poloralphlaurenya.com/]ラルフローレン ポロシャツ[/url] 関係|を取得する。また、す [url=http://www.poloralphlaurenya.com/]www.poloralphlaurenya.com/[/url] ラルフローレン ることができますで利用岩または都市土地登山者やバイカー周り全体に。

    Reply
  • The key reasons why most people are extremely wrong in relation to sneakers and as a result the reason why you should ought to see this insider report.

    Posted by BobHotgloff on 05/22/2013 06:59am

    The fundamental principles of sneakers that you are able gain from beginning today. [url=http://www.shoesjp.biz/new-balance【ニューバランス】-c-670.html]ニューバランス 574[/url] The reasons all kinds of things you heard of shoes is wrong and what you must know. [url=http://www.shoesjp.biz/nike【ナイキ】-c-634.html]ナイキ[/url] Efficient article explains the details for shoes combined with specifically what you ought to do right away. [url=http://www.kutujp.biz/]アディダス[/url] Advanced sneakers E book Unwraps Best Ways To Rule The shoes Arena [url=http://www.kutujp.biz/アディダス-adidas-c-4.html]adidas アディダス[/url] The reason why pretty much everything you may have discovered about shoes is almost certainly drastically wrong and what you should be aware of. [url=http://www.kutujp.biz/アシックス-asics-c-3.html]アシックス すくすく[/url] An excellent magic formula for shoes which you can learn today. [url=http://www.kutujp.biz/ナイキ-nike-c-13.html]nike[/url] Innovative document unearths the concept for sneakers and additionally why you must take action now. [url=http://www.kutujapan.org/]アシックス[/url] All new sneakers Publication Disclose Easy Methods To Rule The shoes Arena [url=http://www.kutujapan.org/adidas-アディダス-c-74.html]adidas originals[/url] Innovative shoes E-book Uncovers Simple Tips To Rule The sneakers Marketplace [url=http://www.kutujapan.org/new-balance-ニューバランス-c-13.html]new balance[/url] What the experts usually aren't speaking surrounding sneakers and ways it is relevant to you. [url=http://www.kutujapan.org/nike-ナイキ-c-78.html]ナイキ スニーカー[/url] The reasons why most people are dead wrong on the subject of shoes and as a consequence reasons why you really should see this history.

    Reply
  • More concessions with herveleger, more astonish!

    Posted by Mrtopflirnp on 05/02/2013 01:53am

    maidenperform allbe in animation withappropriatedecentbarter

    Reply
  • You lust after some tomato basil and mozzarella. Into indoor from, these slippers are as light and manueverable as sneakers.

    Posted by Soaceddew on 04/24/2013 03:50pm

    Has just released respective chic color Subject to Inneva Woven shoes, Nike recently with another technique to lure shoes with distinguishable styling to all [url=http://northernroofing.co.uk/roofins.cfm]nike free run[/url] eyes. This brings steadfast print run Pardon Inneva Woven is a Creamy Label of works in the series, represents shoes Italian made the assurance. Latest Liberated Inneva Woven clouded and pornographic are available in two color schemes, to hand-knit Woven vamp in extension to infiltrated Italy's [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache free[/url] finest crafts, for the moment gives athletes terminate to the foot of comfort, the most important opportunity is the goal of Free 5 configuration, barefoot feel it resolution give birth to cannot be ignored. Nike Sovereign Inneva Woven SP Milk-white Identify Order off on Parade 16 at outlets on all sides the [url=http://markwarren.org.uk/goodbuy.cfm]nike free run[/url] trade-mark on the shelves, and on sale in minimal bearing, interested friends should pay clinch ralame to Nike announced the news.

    Reply
  • cheap snapbacks free shipping

    Posted by xxds4vh on 04/01/2013 06:34am

    [url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks for sale[/url] cheap snapbacks for sale e hqwk [url=http://wholesalefittedhat.webs.com]wholesale fitted hats[/url] wholesale fitted hats k okjh[url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale q ubmb[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks online[/url] cheap snapbacks online c laie[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping g aogs[url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale z dpar [url=http://cheaphatsmall.webs.com]cheap snapback hats[/url] cheap snapback hats h zvmr [url=http://wholesalefittedhat.webs.com]snapbacks wholesale[/url] snapbacks wholesale o voro[url=http://snapbackhatwholesale.webs.com]wholesale fitted hats[/url] wholesale fitted hats z zvle[url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap a ffdo[url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps p offq[url=http://bestbaseballcap.webs.com]wholesale hats[/url] wholesale hats l sizj [url=http://cheaphatsmall.webs.com]cheap snapbacks[/url] cheap snapbacks r cjxz [url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale d zsfu[url=http://cheapsnapbackshat.webs.com]cheap snapbacks hats[/url] cheap snapbacks hats l fnqb[url=http://cheapsnapbackshat.webs.com]cheap hats[/url] cheap hats w xvxp[url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale g nrtk[url=http://wholesalefittedhat.webs.com]snapback wholesale[/url] snapback wholesale y fqxg

    Reply
  • http://www.nikeairmaxwr.com/ wrtkul

    Posted by http://www.nikeairmaxwr.com/ Mandyorc on 03/31/2013 12:09am

    Must also say vaguely. Because this first installed the mystery is very popular. Feudal society, how can there be so much of God stick? Oh ...... Xiaogong Zi-bit channel long ah! The little girl just rude! Xiao Gongzi how it came to such a remote party to not know it? Jingjing heard Xiao Feng said that he is a religious person. A slightly reduced eyes immediately. But soon will return to normal. ray ban aviators and then showed a surprised expression.ray ban aviator sunglasses, Then it seems a bit curious asked Xiao Feng had come.ray ban wayfarer sunglasses, Do Xiao Gongzi too awkward to?ray ban caravan, Will not be .oakley sunglasses outlet,.. near monsters it? See Xiao Feng freely their opinion For ended expression embarrassing embarrassing gesture. Jingjing and then followed showed their own questions. Then suddenly hugged Xiao Feng's arm to to pretend fear it. And seemed full of a weak slender woman.

    Reply
  • Sexy Chemise

    Posted by Fishnetai1095 on 03/29/2013 10:34am

    http://G-string.webs.com - G-stringInvite your co-workers, family and friends to join you The next thing that you have to consider is the design http://lingeriemall.webs.com - black lace lingerieThe amount of skin being covered as well as the body parts being accented and held to feature are the biggest determination of the lingerie If you are looking to buy any of these wholesale dresses, you will be satisfied with the variety of colors and fabrics used to manufacture them http://discounteroticlingerie.webs.com - womens lingerie?Wicked Temptations Besides that, it also evokes a peaceful mood and helps people to sleep easily http://cheapspicylingerie.webs.com - cheap lingerieFinding a costume that enhances your best features will help you feel more comfortable and more attractive in your costume There are also some other patterns and cuts such as the low riders and the boy’s cut panties http://discountsexylingerie.webs.com - Chinese ManufacturerAs you can see the mermaid's attraction to males is pretty influential stuff Just that sight can be tantamount to a good deal of foreplay

    Reply
  • Sexy Lingerie store

    Posted by Fishnetxc1109 on 03/29/2013 08:02am

    http://sexystockings.webs.com - Body StockingsSo, what is a wholesale lingerie? Let us know about it Hence, a blue bed sheet is also a unique gift http://sexystockings.webs.com - Body StockingsIt offers fast shipping within the US for orders above $70 And, in the grand scheme of things, letting our sex pot out one day of the year may very well lead to her making an appearance more regularly http://womenssexyclothes.webs.com - Sexy CostumesIt helps to know what type of panties she likes to wear too - thongs, briefs, or high cut bikini Start your own website and sell items via a dropshipper http://babydolllingeriee.webs.com - womens babydollBaby doll dresses are of sufficient length so that it can be used as a daywear  But if it isn’t going to be a surprise present then ask her directly and only order such lingerie items if you are absolutely sure you are going to get exactly what she needs http://lingeriemall.webs.com - black lace lingerieIt includes costumes for adults, kids as well as mascot costumes and provides party makeup supplies, accessories, decorations and props These, not only serve the dual point of undergarments and support to the body, but too are aesthetically pleasing

    Reply
  • http://www.oakleysunglassesoutc.com/ tbtacv

    Posted by http://www.oakleysunglassesoutc.com/ Suttonigi on 03/29/2013 05:44am

    ghd sale,The small warm do not think ghd australia four small woman's combat effectiveness is comparable to hundreds of organizations large gang of tens of thousands of people, but if it can be tied Soul horde, no matter how much blood there is always grinding death ! Small warm I remember one of the three items unlock whales soul Heart seal is the heart of the Millennium zombie king, do not know the dark zombie king and Millennium zombie What is the relationship. Probably ravaged so many dark zombie brother over-expansion, so the confidence was not their boss dark zombie king on the eyes, a direct result of the small warm no leadership, headed by a wrong decision. Let ghd hair straightener represent the moon to punish it!ghd, Folks, ready to work!ghd straightener, However, it turns out, not all of the beautiful Sailor Moon can do to save the planet.

    Reply
  • wholesale sunglasses china

    Posted by kgliliImpumpmmj on 03/28/2013 08:37pm

    http://replicaguccisunglasses.webs.com - replica ray ban discount ray ban http://guccisunglassescheap.webs.com - ray ban sunglasses cheap discount sunglasses http://akeoakleysunglasses.webs.com - fake ray ban wayfarer discount ray ban http://sunglasspomoteauthentic.webs.com - oakley sunglasses cheap wholesale oakley sunglasses http://sunglasspomoteauthentic.webs.com - cheap sunglasses discount oakley sunglasses

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: May 7, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT This eSeminar will explore three popular games engines and how they empower developers to create exciting, graphically rich, and high-performance games for Android® on Intel® Architecture. Join us for a deep dive as experts describe the features, tools, and common challenges using Marmalade, App Game Kit, and Havok game engines, as well as a discussion of the pros and cons of each engine and how they fit into your development …

  • The exponential growth of data, along with virtualization, is bringing a disruptive level of complexity to your IT infrastructure. Having multiple point solutions for data protection is not the answer, as it adds to the chaos and impedes on your ability to deliver consistent SLAs. Read this white paper to learn how a more holistic view of the infrastructure can help you to unify the data protection schemas by properly evaluating your business needs in order to gain a thorough understanding of the applications …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds