Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

When using LINQ to XML to query elements defined with a namespace, you need to specify the namespace explicitly. The following example shows how you can do so using the XNamespaceelement and then using it in your code:

XDocument rss =

XDocument.Load(@"http://www.wrox.com/WileyCDA/feed/RSS_WROX_ALLNEW.xml");

XNamespace dcNamespace = "http://purl.org/dc/elements/1.1/";

var posts =

from item in rss.Descendants("item")

select new {

Title = item.Element("title").Value,

URL = item.Element("link").Value,

Creator = item.Element(dcNamespace + "creator").Value

};

foreach (var post in posts) {

Console.WriteLine("{0}", post.Title);

Console.WriteLine("{0}", post.URL);

Console.WriteLine("{0}", post.Creator);

Console.WriteLine();

}

Figure 14-17 shows the query result.

Figure 1417 Retrieving Postings in the Last 10 Days The element in the RSS - фото 206

Figure 14-17

Retrieving Postings in the Last 10 Days

The element in the RSS document contains the date the posting was created. To retrieve all postings published in the last 10 days, you would need to use the Parse()method (from the DateTimeclass) to convert the string into a DateTime type and then deduct it from the current time. Here's how that can be done:

XDocument rss =

XDocument.Load(

@"http://www.wrox.com/WileyCDA/feed/RSS_WROX_ALLNEW.xml");

XNamespace dcNamespace = "http://purl.org/dc/elements/1.1/";

var posts =

from item in rss.Descendants("item")

where (DateTime.Now -

DateTime.Parse(item.Element("pubDate").Value)).Days < 10

select new {

Title = item.Element("title").Value,

URL = item.Element("link").Value,

Creator = item.Element(dcNamespace + "creator").Value,

PubDate = DateTime.Parse(item.Element("pubDate").Value)

};

Console.WriteLine("Today's date: {0}",

DateTime.Now.ToShortDateString());

foreach (var post in posts) {

Console.WriteLine("{0}", post.Title);

Console.WriteLine("{0}", post.URL);

Console.WriteLine("{0}", post.Creator);

Console.WriteLine("{0}", post.PubDate.ToShortDateString());

Console.WriteLine();

}

LINQ to SQL

LINQ to SQL is a component of the .NET Framework (v3.5) that provides a runtime infrastructure for managing relational data as objects.

With LINQ to SQL, a relational database is mapped to an object model. Instead of manipulating the database directly, developers manipulate the object model, which represents the database. After changes are made to it, the object model is submitted to the database for execution.

Visual Studio 2008 includes the new Object Relational Designer (O/R Designer), which provides a user interface for creating LINQ to SQL entity classes and relationships. It enables you to easily model and visualize a database as a LINQ to SQL object model.

Using the Object Relational Designer

To see how LINQ to SQL works, create a new Windows application using Visual Studio 2008.

First, add a new LINQ to SQL Classes item to the project. Use the default name of DataClasses1.dbml(see Figure 14-18).

Figure 1418 In Server Explorer open a connection to the database you want - фото 207

Figure 14-18

In Server Explorer, open a connection to the database you want to use. For this example, use the pubssample database. Drag and drop the following tables onto the design surface of DataClasses1.dbml:

authors

publishers

titleauthor

titles

Figure 14-19 shows the relationships among these four tables.

Figure 1419 Now save the DataClasses1dbmlfile and Visual Studio 2008 will - фото 208

Figure 14-19

Now save the DataClasses1.dbmlfile, and Visual Studio 2008 will create the relevant classes to represent the tables and relationships that you just modeled. For every LINQ to SQL file you added to your solution, a DataContextclass is generated. You can view this using the Class Viewer (View→Class View; see Figure 14-20). In this case, the name of the DataContextclass is DataClasses1DataContext. The name of this class is based on the name of the .dbml file; if you named the .dbmlfile Pubs, this class is named PubsDataContext.

Figure 1420 Querying With the database modeled using the LINQ to SQL - фото 209

Figure 14-20

Querying

With the database modeled using the LINQ to SQL designer, it's time to write some code to query the database. First, create an instance of the DataClasses1DataContextclass:

DataClasses1DataContext database = new DataClasses1DataContext();

To retrieve all the authors living in CA, use the following code:

var authors = from a in database.authors

where (a.state == "CA")

select new {

Name = a.au_fname + " " + a.au_lname

};

foreach (var a in authors)

Console.WriteLine(a.Name);

To retrieve all the titles in the titlestable and at the same time print out the publisher name of each title, you first retrieve all the titles from the titlestable:

var titles = from t in database.titles

select t;

And then you retrieve each title's associated publisher:

foreach (var t in titles) {

Console.Write("{0} ", t.title1);

var publisher =

from p in database.publishers

where p.pub_id == t.pub_id

select p;

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x