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 );

Inititalize array in C#

Maybe this post is not necessary, but I still have thought that beginners will struggle with array initialization and C# objects.

Here we go with an Int array first,

Syntax: Type [] <variable>;

I am combining declaration with an assignment of values as follows

 int[] x = new int[] { 1, 2 };

Object Array

What about object array? Let’s have a look at the Account Class

class Accounts
 public Accounts()
 // TODO: Complete member initialization

This is a blank class with only one default constructor. We are going to create an array of Accounts with size 2.

 Accounts[] ac = new Accounts [] { new Accounts( ),
 new Accounts( ) 

Here in all these arrays, we have explored the size will be automatically determined while we initialize the values dynamically to some extent.