smart developer’s blog

This is a C# resource library! Free how to’s and best practices…

Posts Tagged ‘Filter

Linq in DataSet

with 2 comments

I recently had to filter and order some datasets. I used Linq and I found it to be very nice.
Here are a few examples:

1. If you have a dataset with a table containing products and you want to search for all products having “test” in their name, and order the list by creation date, you can use something like:


DataTable dt = ds.Tables[0]
			.AsEnumerable()
			.Where(o => o.Field<string>("Name").Contains("test"))
			.OrderBy(o => o.Field<DateTime>("CreationDate"))
			.CopyToDataTable();

2. Alternatively, if you have to order a report each time a column name is pressed, you can write you own method that orders a table by a given column:


private DataTable OrderDataTable<T>(DataTable dt, string orderby, string orderdir)
	{
	if(orderdir == "ASC")
		return dt.AsEnumerable().OrderBy(o => o.Field<T>(orderby)).CopyToDataTable();
	else
		return dt.AsEnumerable().OrderByDescending(o => o.Field<T>(orderby)).CopyToDataTable();
	}

and you can use it like this:


switch (orderby1)
	{
	case "Keyphrase":
		repMain.DataSource = OrderDataTable<String>(ds.Tables[0], orderby1, orderdir1);
		break;
	case "KEI":
		repMain.DataSource = OrderDataTable<Double>(ds.Tables[0], orderby1, orderdir1);
		break;
	default:
		repMain.DataSource = OrderDataTable<Int32>(ds.Tables[0], orderby1, orderdir1);	
		break;
	}

Have fun!

Written by smartdev

May 8, 2009 at 9:36 am

Posted in .Net, Programming

Tagged with , , ,