DataView.ToTable method in the 2.0 Framework
This is a really simple trick but it's way cool. Now that I have some time again, I've been trying to get up to speed with LINQ and ADO.NET 2.0. God I missed it. Anyway, this comes up in the newsgroups all the time so I figured I'd write up a quick sample to point to.
Problem: I want to create a new datatable with only a subset of the columns of the original datatable.
Solution: Thanks to the ADO.NET team, it's cake:
class Program
{
private static Actresses DemoData = new Actresses();
static void Main(string[] args)
{
LoadData();
DataTable dt = DemoData.Stars.DefaultView.ToTable("Stars", true, new String[]{"FirstName", "LastName"});
foreach(DataRow dro in dt.Rows){
foreach(DataColumn dc in dt.Columns){
Console.WriteLine(dro[dc].ToString());
}
}
Console.ReadLine();
}
static void LoadData(){
Actresses.StarsRow dro = DemoData.Stars.NewStarsRow();
dro.FirstName = "Jenna";
dro.LastName = "Jameson";
dro.LovesBill = true;
DemoData.Stars.AddStarsRow(dro);
dro = DemoData.Stars.NewStarsRow();
dro.FirstName = "Tera";
dro.LastName = "Patrick";
dro.LovesBill = true;
DemoData.Stars.AddStarsRow(dro);
dro = DemoData.Stars.NewStarsRow();
dro.FirstName = "Aishwarya";
dro.LastName = "Rai";
dro.LovesBill = true;
DemoData.Stars.AddStarsRow(dro);
}
}
All that you need to do is create a view or use the default view, then call its ToTable method passing in a table name and a String array of the column names you want to populate in the new table. There are four overloads and since i love dataviews, I'm going to flesh out a few in depth articles doing some much less basic stuff. (Spoiler - There's a Distinct argument).