Monday, July 6, 2009

LINQ: How to use SQL TOP query in LINQ

I was looking for this particular feature in LINQ from the time i started using it in .Net 3.0, but not able to find a direct API, but now with .Net 3.5, it looks very simple.

When i found it for my new application a week back i was really happy mainly to avoid the workaround it requires to achieve the same.

Assume you have a List of objects or data as below

IList dataList = new List();
dataList.Add("14");
dataList.Add("22");
dataList.Add("35");
dataList.Add("4");
dataList.Add("10");
dataList.Add("60");

Now if you want to select top 2 records, u have to use Take(int count) method at the end of your LINQ query as listed below.

var topList = (from data in dataList
select data).Take(2);

This method takes any integer value and returns as many records available within the count.
Luckily i didn't get any exception when i gave 20 as a input to this method, for my analysis purpose:)

Well, for me this method should have taken unsigned int, instead of int type as i find no meaning to have int type

No comments:

Post a Comment