Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts
Monday, 29 April 2013

Use .Any() in your LINQ to SQL queries

When using LINQ to SQL to check whether either no records exist or at least 1 record exists, be sure to prefer Any() over Count() as the SQL will be optimised to only get the information required. Any() will use EXISTS in SQL which stops as soon as a record is found whereas Count() uses COUNT(*) which goes through all the records to get the number matching the query.

Consider the following code samples:

var q1 = TableName.Count() > 0;

var q2 = TableName.Any();

They will produce the following SQL:

-- q1
SELECT COUNT(*) AS [value]
FROM [TableName] AS [t0]

-- q1
SELECT
    (CASE
        WHEN EXISTS(
            SELECT NULL AS [EMPTY]
            FROM [TableName] AS [t0]
            ) THEN 1
        ELSE 0
     END) AS [value] As you can see the second sample produces some admittedly uglier SQL but is much more efficient.
 
Sunday, 28 April 2013

Merging Dictionary objects

Say you have two (or more) Dictionary objects and want their contents merged, this can be done with LINQ very conveniently like so.

var mergedDictionary = dictionaries
    .SelectMany(e => e)
    .ToLookup(e => e.Key, e => e.Value)
    .ToDictionary(e => e.Key, e => e.First());

There is a major issue with this method though in that it's quite horrible performance-wise, the reason being because of the amount of conversions and unnecessary work that is happening. Firstly SelectMany is flattening the IEnumerables into a single IEnumerable, then we're converting the new IEnumerable into a Lookup and then we're converting the Lookup into a Dictionary taking only the first value for any key in the Lookup to resolve duplicates.

This is one of the problems with LINQ, everything is so simple and easy to use, but if you don't understand what is going on then a LINQ query can have a serious hit on the performance of an algorithm.