50 LINQ Examples, Tips and How To's

Posted by: Suprotim Agarwal , on 6/27/2011, in Category LINQ
Views: 444712
Abstract: I have been writing some LINQ tutorials, tips and How To's on my blog and most of these posts contain short snippets that can be used in your project or that demonstrate how to use LINQ effectively. I wanted to share them with my readers over here. These short examples demonstrate how to use a particular LINQ feature and are listed over here in no particular order.

I have been writing some LINQ tutorials on www.devcurry.com and most of these posts contain short snippets that can be used in your projects or demonstrate how to use LINQ effectively. I wanted to share them with my readers over here. These short examples demonstrate how to use a particular LINQ feature and are listed over here in no particular order.


Update: Thanks to John Flynn, these examples are now also available in LINQPad. Check 50 LINQ Examples Now in LINQPad 

Click to Retweet this link and let fellow developers know about this useful resource

List<T>.ConvertAll<>() with Lambda Expression - List<T> has many useful methods for dealing with sequences and collections. One such method is the ConvertAll<>() method. All those who have used the List<T>.ConvertAll<>() are aware how useful this method is to convert the current List<T> elements to another type, and return a list of converted elements. However, an instance of a conversion delegate must be passed to this method, which knows how to convert each instance from the source type to the destination type

Calculate the Size of a Folder/Directory using .NET 4.0 - .NET 4.0 introduces 7 New methods to Enumerate Directory and Files in .NET 4.0. All these methods return Enumerable Collections (IEnumerable<T>), which perform better than arrays. We will be using the DirectoryInfo.EnumerateDirectories and DirectoryInfo.EnumerateFiles in this sample which returns an enumerable collection of Directory and File information respectively. Here’s how to calculate the size of a folder or directory using .NET 4.0 and LINQ.

LINQ: Generate Odd Numbers using Parallel Execution - A couple of months ago, I had written on Generate Odd Numbers within a Range using LINQ. In that post, I had demoed how to ‘sequentially’ generate odd numbers within a Range. However what if you have to generate a large set of numbers and are not interesting in generating the numbers in a sequence, you can use Parallel Execution

LINQ: Compare two Sequences - How do you compare two sequences using LINQ? The answer is by using the Enumerable.SequenceEqual(). SequenceEqual() compares the source and target sequences elements, by using the default equality comparer for their type, and returns a Boolean.

LINQ: Calculate Average File Size in C# - Let us see a simple code using LINQ and C# that calculates the average FileSize of the files kept in a folder.

LINQ: Generate a Cartesian Product - A Cartesian product by definition is a direct product of two sets. Let us see how to achieve something similar in LINQ using the SelectMany method

LINQ: List Classes implementing the IEnumerable Interface – A reader wanted to know an easy way to find all the types that implement the IEnumerable interface, or for that matter, any interface. Here’s a piece of LINQ code that lists all the types implementing the IEnumerable interface

Find Uppercase words in a String using C# - I am helping a friend to build an Editor API in C#. One of the functionalities in the Editor is to filter uppercase words in a string and highlight them. Here’s a sample of how uppercase words can be filtered in a string

LINQ: Query Comma Separated Value (CSV) files - In this post, we will read a Comma Separated Value (CSV) file using LINQ and perform some calculations on the data.

Generate Odd Numbers within a Range using LINQ - The Enumerable.Range method generates a sequence of integral numbers within a specified range. Here’s how to use it to generate a sequence of odd numbers within a given range say 20 to 40

Generate Sequence of Float Numbers within a Range using LINQ - A small modification to the previous post and use LINQ to generate float numbers within a Range say - 20 to 40.

Query a Sequence using LINQ - In the previous posts, we saw how to Generate Sequence of Float Numbers within a Range using LINQ. In this post, let us see how to query this sequence and extract elements based on a condition

Divide Sequence into Groups and Query using LINQ – In the previous link, I had blogged about Querying a Sequence using LINQ. Now let us say if this sequence was to be divided into smaller sequences/batches and then queried upon, here’s how we would do it using LINQ

LINQ – Left Join Example in C# - In this post, we will see an example of how to do a Left Outer Join in LINQ and C#.

Inner Join Example in LINQ and C# - Let see an example of using the Join method in LINQ and C#. The Join method performs an inner equijoin on two sequences, correlating the elements of these sequences based on matching keys. It is called equijoin, since we are testing for equality using the equals operator.

Using from-let-where Clause in LINQ - In this example, we will see how to use the from-let-where clause in LINQ. For this purpose, let us take a sample array and then print only those numbers in this array, whose square is greater than 10

List all .NET Attributes in the Loaded Assemblies - Here’s how to list all the .NET Attributes in assemblies that are loaded in your application

Rewrite Nested ForEach Loop in LINQ - Let’s assume you have two string array's of the same length and you need to loop through each element of the array and concatenate it’s elements. One way to do this is to use nested foreach loops

Count File Extensions and Group it using LINQ - We have this application where a service reads files generated in a folder every hour and returns a string array containing the file names. A simple report needed to be generated which showed the count of files grouped by the file extension

Swap Words inside a String using LINQ - I was working on a piece of code where the name of the person was stored like “FirstName, LastName”. The requirement was to swap these two words and instead make it look like “LastName, FirstName”

Filter a Type in .NET inside the For-Each Loop - Here’s a nice way to filter an ArrayList right inside the For-Each Loop. We have to filter and print only ‘integers’ greater than 10.

Split a String Collection into Groups using LINQ - I was recently working on an interesting problem which involved splitting a string collection into groups. We had a huge collection of email addresses stored in a string array. The task was to loop the array and select 10 emails at a time and send it for processing

Highest Value in each Group using LINQ - In this post, I will show you how to fetch the maximum value in each Group using LINQ

Loop through Master-Detail Records using LINQ - Here’s an example of how to loop through Master-Detail Records using LINQ. I have taken the example of one Department containing multiple Employees. The example is taken only for the purpose of understanding and does not cover all scenarios.

Concatenate Unique Elements of two List<String> and Sort using LINQ - Here’s how to concatenate unique elements of two List<String> and then Sort them using LINQ

List all Files in .NET 4.0 Based on the Creation Date – A post that shows how to returns a list of files from a directory for a given date range (i.e. start date - end date).

Skip and Select Elements in a String Array using LINQ - Here’s how to skip and select elements in a string array using LINQ. In the example shown below, we will skip the first two elements of an array and select the next three.

Enumerate Hidden Directories in .NET 4.0 - Let us see a practical example of using the DirectoryInfo.EnumerateDirectories to list the names of only hidden directories in a drive

Ordering Elements of a List<String> by Length and Content - Here’s how to order the elements of a List<String> first by length and then by content

Distinct OrderBy in LINQ - One of my colleagues was curious to know how to implement a Distinct-OrderBy on a custom collection in LINQ. Here’s an example. This example uses the Distinct and OrderBy on the CustomerName property of the Customer class.

Using LINQ to select Only Strings from an ArrayList - Here’s a simple example of using LINQ to select only Strings from an ArrayList that contains both integers and strings

Combine Multiple Sequences in LINQ using the Zip Operator - .NET 4.0 - To merge the elements of sequences, use the Zip operator that is new in .NET Framework 4.0

Sort a String Array containing Numbers using LINQ - Here’s how to use LINQ to sort a String Array containing Numbers

Join Two String Arrays with Distinct values using LINQ - One of my colleagues was looking out for a simple way to join two string arrays and avoid duplicates (if any) in those arrays. I asked him to use the Union method which excludes duplicates from the return set.

Using TrueForAll with Generic Lists - If you work with generic lists, you’ll know sometimes you need to check the values in the list to see if they match certain criteria. A method I don’t see used allot is TrueForAll (by Malcolm Sheridan).

Determine all Types that Implement an Interface - I recently saw an interesting discussion on a forum. The discussion was about finding all the types that implement a particular interface. Here’s a code that lists all the types implementing a particular interface

Using LINQ to Find Top 5 Processes that are Consuming Memory - A user on a forum recently asked me how to find the processes that were currently running. A quick look at MSDN led me to the Process object. The Process provides access to local and remote processes and enables you to start and stop local system processes. Here’s how to find out the top five processes that are consuming memory (by Malcolm Sheridan).

Find Distinct Text Using LINQ - Another good use for LINQ popped up today in the forums. The person asked how to get distinct values from a series of text. I once again said LINQ! (by Malcolm Sheridan).

Using LINQ to Search and Delete Old Files - I was recently asked on the asp.net forum about ways to find old files and delete them. I said use LINQ. It is perfect for this scenario.

Using LINQ to Find the Sum of a MultiDimensional Array - Here’s how to the find the sum of a multidimensional array using LINQ. This array has 3 rows and 2 columns

Get Unique Selected Items From Multiple ASP.NET ListBox and Merge them using LINQ - I recently did a short article on Get Selected Items From Multiple ASP.NET ListBox and Merge the results using LINQ. A user pointed out what if you wanted only the unique values from each list. Well here are two options to do that (by Malcolm Sheridan).

How to Sort Data using LINQ - I have been asked allot of questions in the forums lately about LINQ and one question that comes up is how to sort data. A user had an ArrayList of employees and he needed to order them by surname.

Retrieve Selected Items of an ASP.NET ListBox using LINQ - A user ‘JukeBox’ mailed back asking me if it was possible to retrieve the selected items of a ListBox using LINQ. Here’s how to do so

Replicating the 'IN' operator in LINQ - We often use the 'IN' Operator to specify multiple values in the WHERE clause. What if you have to do something similar in LINQ. Here's a simple example that demonstrates this. The example searches out the desired pincodes in a list of Booth Addresses.

Implementing Paging in a Generic List using LINQ - It's quite common of users to bind their Generic List to an ASP.NET control. However if the list is huge, you may need to implement Paging functionality. Here's a simple way to do implement Paging functionality using LINQ


LINQ to XML Sorting - In this post, we will read data from the XML file using LINQ to XML, sort it by an element and then load it into a Dictionary.

Serialize XDocument in LINQ To XML - In this post, we will first create an XDocument object that contains XElement objects. You can then serialize the XDocument to a File, XMLWriter or TextWriter

Select Last N elements using LINQ to XML - Here’s a simple example of selecting the last ‘N’ elements of a XML document using LINQ to XML

Create a XML Tree from a String - I got a mail from a devcurry.com reader Martin this morning who asks me “I have a string containing XML tags and I need to create a XML document out of it without much efforts. Is there an easy way to do so. I can assure that the string contains valid xml”. Yes, there is an easy way to do so.

LINQ To XML Tutorials with Examples – A set of 24 examples to teach you LINQ to XML

Hope you found this list useful! Thanks for reading this article.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Mike Long on Sunday, July 3, 2011 6:09 AM
Excellent examples. Can you also give an example of converting a LINQ query to PLINQ?
Comment posted by Suprotim Agarwal on Monday, July 4, 2011 11:42 PM
Mike: I wrote an article to explain the same http://www.dotnetcurry.com/ShowArticle.aspx?ID=730
Comment posted by Manish T on Monday, April 16, 2012 8:06 AM
all examples are really good, it help me a lot
Comment posted by mkmanibose.s@gmail.com on Wednesday, April 18, 2012 4:37 AM
very nice article
Comment posted by anthony ogbechie on Wednesday, October 24, 2012 8:51 AM
hi..please i'm new to c# and i have this project i'm working on..and its really difficult..its a c# program to group all equal files in a directory
(equal meaning i have to read all files byte by byte) i dont know what to do please help...
Comment posted by Vijay on Sunday, November 4, 2012 10:22 AM
.net scope in windows programming
Comment posted by jhgkghjkghjk on Friday, December 7, 2012 6:47 AM
Comment posted by aasmin on Thursday, March 14, 2013 3:16 AM
Comment posted by 3243 on Monday, October 7, 2013 5:37 AM
Comment posted by adibi on Tuesday, October 29, 2013 2:13 AM
would you visit my question?
Comment posted by aaaaa on Tuesday, March 25, 2014 4:27 AM
not that much expected level
Comment posted by n.soundar on Sunday, September 14, 2014 8:10 AM
examples are fantastic articles and cleared my many doubts and gave me ideas; thanks a lots,keep it up