Monday, November 3, 2008

Using LINQ and Lambda expressions in Compact Framework 3.5

I tried adding a reference to System.Linq in my class but was not able to find the reference and was aghast at this. Then I found that to add a reference to System.Linq, first we should add a reference to the System.Core.dll using the Add Reference option. Then add
using System.Linq;
in the class file.
I had a requirement to filter out an array based on certain conditions , populate a struct and then bind the data to a list view.
Consider a simple example where I have an array with different Temperature Zones such as Hot, Cold and want to sum all the temperatures in hot and cold and display.
My Array[0].TempZone = "hot";
MyArray[0].Temperature = 30;
My Array[1].TempZone = "hot";
MyArray[1].Temperature = 40;
My Array[2].TempZone = "Cold";
MyArray[2].Temperature = 40;
My Array[3].TempZone = "Cold";
MyArray[3].Temperature = 50;
In this case, only 2 rows should be displayed in the list view with TempZone as Hot and Temperature as 30 + 40 = 70 and second row with TempZone as Cold and Temperature as 40 + 50 = 90.
I have a struct to fill in from the array
Struct MyStruct
{
String tempZone;
Int finalTemp;
}
To achieve this I used a simple LINQ query
var hotlist = from item in MyArray where item.TempZone == "hot" select item;
var coldlist = from item in MyArray where item.TempZone == "Cold" select item;
And then used Lambda expressions to obtain the sum as
lMystruct = new MyStruct[2];
lMystruct[0].TempZone = "hot";
lMystruct[0].Temperature = hotlist.Sum(hot => hot.Temperature);
lMystruct[1].TempZone = "Cold";
lMystruct[1].Temperature = coldlist.Sum(cold => cold.Temperature);
which is pretty simple and the struct can now be bound to a listview.
There may or may not be more than row with hot or cold and not necessarily in the same order in which case .Net code becomes pretty complex.

No comments: