Wednesday, 5 March 2014

50 LINQ Examples, Tips and How To's

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
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.

3 comments:

  1. Speeding up LINQ to SQL
    There are a number of ways to improve the performance of LINQ to SQL queries.

    1. Cache the Mapping Source
    When executing large LINQ to SQL queries (those involving many tables), LINQ to SQL's object relational mapper incurs a significant overhead in building the internal metamodel. The metamodel describes how your entity classes map to the underlying tables and columns, and is built automatically via reflection (assuming you're using attributes rather than an XML file, to map tables and columns). Ordinarily, this overhead is incurred every time you instantiate a DataContext, which is not great for performance. You can avoid this by manually specifying a single static MappingSource object for all typed DataContext instances as follows:

    public class MyDataContext : DataContext
    {
    static MappingSource _sharedMappingSource = new AttributeMappingSource();

    public MyDataContext (IDbConnection cx) : base (cx, _sharedMappingSource) { }
    public MyDataContext (string cxString) : base (cxString, _sharedMappingSource) { }
    }
    You might wonder what happens in a multithreaded environment. What if two threads (e.g., from two different client requests) instantiate their own instances of MyDataContext and start executing queries at the same time? Fortunately, everything works correctly because MetaModel instances are thread-safe. I've used this technique in a large CRM application that uses LINQ to SQL almost entirely for data access: the system has over 500 users and has been running without trouble since early 2008. (Without this optimization, some queries were simply too slow for LINQ to SQL to be viable).

    Note that although MetaModel (MappingSource) instances are thread-safe, the same is not true for DataContext instances. You cannot share a single DataContext instance between multiple threads, or things will go terribly wrong! (And not that you'd want to: doing so would mean taking on unpleasant concurrency issues that are otherwise handled very well by SQL Server itself, through its transaction isolation level semantics).

    2. Use Compiled Queries
    Ordinarily, LINQ to SQL must translate LINQ queries to SQL every time a query executes; this involves recursing the expression tree that makes up the query in several stages. It sounds worse than it is: the computation cost is not enormous in the overall scheme of things (certainly not as big as the cost of building an AttributeMappingSource when lots of entities are involved). Nonetheless, you can avoid paying the price on each query execution by precompiling the query using the CompiledQuery class.

    Here's an example that you can paste directly into LINQPad:

    var cc = CompiledQuery.Compile ((TypedDataContext dc, decimal minPrice) =>
    from c in Customers
    where c.Purchases.Any (p => p.Price > minPrice)
    select c
    );

    cc (this, 100).Dump ("Customers who spend more than $100");
    cc (this, 1000).Dump ("Customers who spend more than $1000");
    3. Use Table-Valued Functions Where Necessary
    Finally, there are some queries for which LINQ to SQL producesless-than-ideal SQL. Furthermore, some SQL queries need optimization hints to get the best performance, and optimization hints are impossible with LINQ to SQL alone. A compromise in these situations is to encapsulate the difficult part of the query in a table-valued function, and then map this function into your typed DataContext class. You can then run LINQ queries over this function, and the queries will be translated to SQL and execute on the server. So, in effect, you're mix SQL and LINQ to SQL in the same query.

    ReplyDelete
  2. If you have linq code that uses the .Count() function to check to see if an item exists then you can use .Any() to do the same thing, just faster.

    replace code like this:

    var query = (from cust in Customer
    where cust.CustomerId == customerId
    select cust);
    return (query.Count() == 0);
    with this:

    var query = (from cust in Customer
    where cust.CustomerId == customerId
    select cust); return (query.Any());

    ReplyDelete
  3. Optimizing linq queries with .Any() instead of .Count()
    If you have any linq code that looks like this:


    1
    2
    3
    4
    var query = (from cust in Customer
    where cust.CustomerId == customerId
    select cust);
    return (query.Count() != 0);
    Replace it with code that looks like this:


    1
    2
    3
    4
    var query = (from cust in Customer
    where cust.CustomerId == customerId
    select cust);
    return (query.Any());
    Basically you save time since linq doesn’t need to count each and every record in the collection.

    ReplyDelete

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...