Menu ▼



Posted By :
avatarmrkraju
Total Views : 829

LINQ query to get top N records using Take() and C#

This example shows you how to get the top N records using LINQ query using C#.

Data:

LINQ query to get top 2 records with max invoice amount

var maxinv = (from res in dt.AsEnumerable()
                orderby res.Field<decimal>("Amount") descending
                select new
                {
                    InvoiceID = res.Field<int>("InvoiceID"),
                    Amount = res.Field<string>("InvoiceNumber"),
                    InvoiceNumber = res.Field<decimal>("Amount"),
                    InvoiceDate = res.Field<DateTime>("InvoiceDate")
                }).Take(2);
gvmax.DataSource = maxinv;
gvmax.DataBind();
output:
InvoiceIDInvoiceNumberAmountInvoiceDate
131INV000131400.2514-01-2015 18:25:00
144INV000144351.4519-01-2015 08:10:20

LINQ query to get top 4 records with min invoice amount

var maxinv = (from res in dt.AsEnumerable()
                orderby res.Field<decimal>("Amount") ascending
                select new
                {
                    InvoiceID = res.Field<int>("InvoiceID"),
                    InvoiceNumber = res.Field<string>("InvoiceNumber"),
                    Amount = res.Field<decimal>("Amount"),
                    InvoiceDate = res.Field<DateTime>("InvoiceDate")
                }).Take(4);
gvmin.DataSource = maxinv;
gvmin.DataBind();
Output:
InvoiceIDInvoiceNumberAmountInvoiceDate
125INV00012595.2512-01-2015 10:10:25
158INV000158100.2519-02-2015 14:35:30
164INV000164146.7523-02-2015 12:11:55
159INV000159160.0121-02-2015 15:08:06





comments powered by Disqus


Search dotnetlearners.com