Книга: C# 2008 Programmer

Reshaping Data

Reshaping Data

Using the new anonymous types feature in C# 3.0, you can define a new type without needing to define a new class. Consider the following statement:

//---query for authors living in CA---
var authors =
 from author in ds.Tables[0].AsEnumerable()
 where author.Field<string>("State") == "CA"
 select new {
  ID = author.Field<string>("au_id"),
  FirstName = author.Field<string>("au_fname"),
  LastName = author.Field<string>("au_lname")
 };

Here, you select all the authors living in the CA state and at the same time create a new type consisting of three properties: ID, FirstName, and LastName. If you now type the word authors, IntelliSense will show you that authors is of type EnumerableRowCollection<'a> authors, and 'a is an anonymous type containing the three fields (see Figure 14-6).


Figure 14-6

You can now print out the result using a foreach loop:

foreach (var row in authors) {
 Console.WriteLine("{0} - {1}, {2}",
  row.ID, row.FirstName, row.LastName);
}

To databind to a DataGridView control, you first must convert the result of the query to a List object:

//---query for authors living in CA---
var authors =
 (from author in ds.Tables[0].AsEnumerable()
 where author.Field<string>("State") == "CA"
 select new {
  ID = author.Field<string>("au_id"),
  FirstName = author.Field<string>("au_fname"),
  LastName = author.Field<string>("au_lname")
 }).ToList();
 //---bind to a datagridview control---
 dataGridView1.DataSource = authors;

Оглавление книги


Генерация: 1.085. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз