smart developer’s blog

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

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]
			.Where(o => o.Field<string>("Name").Contains("test"))
			.OrderBy(o => o.Field<DateTime>("CreationDate"))

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();
		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);
	case "KEI":
		repMain.DataSource = OrderDataTable<Double>(ds.Tables[0], orderby1, orderdir1);
		repMain.DataSource = OrderDataTable<Int32>(ds.Tables[0], orderby1, orderdir1);	

Have fun!


Written by smartdev

May 8, 2009 at 9:36 am

Posted in .Net, Programming

Tagged with , , ,

2 Responses

Subscribe to comments with RSS.

  1. How can you show your codes with the frame?


    May 8, 2009 at 11:40 am

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: