C#Tips/Tricks – Linq and Functions

Do you know Linq in c# has special capabilities to handle data smoothly. As we learned you can operate on user defined types and list using Linq.

Even you can use your own functions from within the Linq

C# Linq

The following example illustrate how to use functions within Linq

 var salesSummary = (from s in salesTable.AsEnumerable()
                           join c in Customer.AsEnumerable() on s.Field<int>("cid").ToString() equals
                           select new
                               sv= new SalesView()
                                   Date = s.Field<DateTime>("date"),                                   
                                   invice = s.Field<int>("vno"),                                   
                                   Customer = c.Field<string>("name"),
                                   Amount = string.Format("{0:0.00}", s.Field<decimal>("amount")),                 
 InvBalance = string.Format("{0:0.00}", GetActBalance(s.Field<DateTime>("date"), s.Field<int>("cid"), s.Field<string>("vno"))),                  

In the above example I used a function GetActBalance to display, the invoice balance at the point of sale , assume that they may paid some amount at the time of sale.

C#Tips/Tricks – Linq to array

You can easily convert a data table rows into object array using Linq query in C#.Net

var names_array = (from cols in tblcols.AsEnumerable() select cols.Field<string>("student_name")).ToArray();

Array can be used to supply items to list box and combo box controls as follows

 listbox1.Items.AddRange(names_array );