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:
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.
Avoiding FOREACH on Collections to Filter for Data
You can avoid the
FOREACHand theIFclauses inside yourFOREACHto 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;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)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.
Let Go the IComparer<T> for Sorting
We no more need to write the tough
IComparerclasses to sort our custom data. We can now use theOrderBymethod 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
ThenByDescendingoperator too.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.Rangemethod.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();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)); }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
ToArrayMethod 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(); }The Let Keyword
The
LETkeyword 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
LEToperator. 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
LETkeyword.var results= from store in Stores let AveragePrice = store.Sales.Average(s => s.Price) where AveragePrice > 500 select new { Name = store.Name, StoreAveragePrice = AveragePrice };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
RegExMatched 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) { // }Querying ArrayList
You would have found that you cannot run LINQ queries on an
ArrayList. That is because it does not implement theSystem.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 SheetRelated Articles
- Applying The Repository Pattern on LINQ and ADO.NET Entity Framework 4
- Understanding LINQ's Deferred Execution
- Using LINQ with Dynamic Where Clauses

Comments
More concessions with herveleger, more astonish!
Posted by Mrtopflirnp on 05/02/2013 01:53ammaidenperform allbe in animation withappropriatedecentbarter
ReplyYou 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:50pmHas 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.
Replycheap 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
Replyhttp://www.nikeairmaxwr.com/ wrtkul
Posted by http://www.nikeairmaxwr.com/ Mandyorc on 03/31/2013 12:09amMust 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.
ReplySexy Chemise
Posted by Fishnetai1095 on 03/29/2013 10:34amhttp://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
ReplySexy Lingerie store
Posted by Fishnetxc1109 on 03/29/2013 08:02amhttp://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
Replyhttp://www.oakleysunglassesoutc.com/ tbtacv
Posted by http://www.oakleysunglassesoutc.com/ Suttonigi on 03/29/2013 05:44amghd 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.
Replywholesale sunglasses china
Posted by kgliliImpumpmmj on 03/28/2013 08:37pmhttp://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
Replytest
Posted by nugsnidge on 03/26/2013 04:30amHere's A Quick Way To Get beats by dre Know-how http://cheapbeatsbyc.blinkweb.com beats by dre-chick has inspected the most up-to-date formula - how to make big money on your own http://www.finalsiren.com Top secret details about beats by dre that no more than the pro's were aware about. http://cheapbeatsbydrecv.blinkweb.com The latest review reveal the low down for beats by dre and furthermore the reasons you need to take action today. www.celineokjp.com beats by dre helps everybody by integrating plenty of unique features and options. This is a unvaluable item for every enthusiast of beats by dre. ã«ã¤ã´ã£ãã³è²¡å¸ Here is the beats by dre truths your Parents doesn't want one to know about !
Replyghd australia yzgicd
Posted by Suttonzla on 02/13/2013 02:11pm5aLzq ugg hPnb hMfb nike shox sko 4mHfp toms outlet 7oNbh hollister sale uk 9kUwf 2yZwn longchamp 0dElc louis vuitton outlet 1wFif michael kors outlet 8oBvr christian louboutin 4vIqu Chris Culliver Jersey 0fZox 8mQmo 4rSme ghd 0mIfv ugg boots sale
ReplyLoading, Please Wait ...