Saturday, May 26, 2012

Get Last n Records using Linq to SQL

Shout it kick it on DotNetKicks.com
The small post is about getting last n number of record(s) from the database table or from the collection using LINQ.

SQL
To get last n number of record(s) from table I do write the following query on my table records in T-SQL.
SELECT TOP n <fields> FROM Forms WHERE <field> = <data> 
ORDER BY <field> DESC
As you see in above query important thing is using order by with desc keyword means reversing the table records - (mostly we apply the order by desc on the primary key of the table).

LINQ
In LINQ we achieve the same thing with the help of OrderByDescending function and Take function.
var qry = db.ObjectCollection
                     .Where(m => m.<field> == data) 
                     .OrderByDescending(m => m.<field>) 
                     .Take(n); 
In above LINQ query same as sql need to apply the where condition first than make collection reverse using order by function and to get top record you just need to make user of Take function.

But to get the last record for the collection you make use of FirstOrDefault function as below
var qry = db.ObjectCollection
                     .Where(m => m.<field> == data) 
                     .OrderByDescending(m => m.<field>) 
                     .FirstOrDefault(); 

Read about the method use on MSDN

Saturday, May 12, 2012

Extende Array Class with Extension method

Shout it kick it on DotNetKicks.com
Read before start reading post : Extension Methods

Here I am going to discuss about the how you can create the Extension method for the System.Array Class. On MSDN : Array Class - Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in the common language runtime

Note - in example below I use type int but this can be replace by any type you want.
In following Example I have implemented Average method for the array elements of type int.
    public static class ArryaExtension
    {
        public static float Average(this System.Array arr)
        {
            int[] a =  arr.Cast().ToArray();
            return (float)a.Sum()/arr.Length;
        }
    }
To get this extension method work you need to pass the type in type as System.Array. Next I converted the array element to type I want this help me to get the support of IEnumerableinterface methods because System.Array is base class which doesn't implement IEnumerable. So once it get convert to specific type array I can able to access IEnumerable methods like Sum which makes task easy.

Conclusion
You can replace the code in the method for any other type and extend the System.Array class easily as per you requirement.