Tải bản đầy đủ - 0 (trang)
9-16. Compare LINQ DataSet Results

9-16. Compare LINQ DataSet Results

Tải bản đầy đủ - 0trang

CHAPTER 9 ■ DATABASE ACCESS



How It Works

The default result of a LINQ query on a DataSet is an IEnumerable, and LINQ provides

extension methods that operate on this result type to allow you to compare results.



■ Tip See Chapter 16 for more information about LINQ extension methods, recipes for using them, and creating

custom extension methods that you can apply to your own data types.



The three extension methods are Union, Intersect, and Except. In all three cases, you call the

extension method on one result and supply another as the method argument—for example:

IEnumerable result1 = ...LINQ query on a DataSet...

IEnumerable result2 = ...LINQ query on a DataSet...

IEnumerable union = result1.Union(result2)

The Union method combines the contents of the two IEnumerable instances. The

Intersect method returns just those rows that exist in both enumerations. The Except method returns

all of the rows in the first enumeration except those that also exist in the second enumeration.

The result of these methods is another IEnumerable, meaning that you can use the result

to enumerate the data rows or as the basis for a further LINQ query, and you can use the same extension

methods to compare the result against another IEnumerable.



The Code

The following program performs two queries against the same table and then uses the Union, Intersect,

and Except methods to compare the results:

using

using

using

using

using

using



System;

System.Collections.Generic;

System.Linq;

System.Text;

System.Data;

System.Data.SqlClient;



namespace Apress.VisualCSharpRecipes.Chapter09

{

class Recipe09_16

{

static void Main(string[] args)

{

// Create a new SqlConnection object.

using (SqlConnection con = new SqlConnection())

{



474



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



// Configure the SqlConnection object's connection string.

con.ConnectionString = @"Data Source = .\sqlexpress;" +

"Database = Northwind; Integrated Security=SSPI";

// Open the database connection.

con.Open();

// Create the query string.

string query = "SELECT * from Region";

// Create the data set.

DataSet dataset = new DataSet();

// Create the SQL data adapter.

SqlDataAdapter adapter = new SqlDataAdapter(query, con);

// Create the command builder so we can do modifications.

SqlCommandBuilder commbuilder = new SqlCommandBuilder(adapter);

// Populate the data set from the database.

adapter.Fill(dataset);

// Obtain the data table.

DataTable table = dataset.Tables[0];

// Perform the first LINQ query.

IEnumerable result1 = from e in table.AsEnumerable()

where e.Field(0) < 3

select e;

// Enumerate the results of the first LINQ query.

Console.WriteLine("Results from first LINQ query");

foreach (DataRow row in result1)

{

Console.WriteLine("ID: {0} Name: {1}",

row.Field(0), row.Field(1));

}

// Perform the first LINQ query.

IEnumerable result2 = from e in table.AsEnumerable()

let name = e.Field(1)

where name.StartsWith("North")

|| name.StartsWith("East")

select e;



475



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



// Enumerate the results of the first LINQ query.

Console.WriteLine("\nResults from second LINQ query");

foreach (DataRow row in result2)

{

Console.WriteLine("ID: {0} Name: {1}",

row.Field(0), row.Field(1));

}

IEnumerable union = result1.Union(result2);

// Enumerate the results.

Console.WriteLine("\nResults from union");

foreach (DataRow row in union)

{

Console.WriteLine("ID: {0} Name: {1}",

row.Field(0), row.Field(1));

}

IEnumerable intersect = result1.Intersect(result2);

// Enumerate the results.

Console.WriteLine("\nResults from intersect");

foreach (DataRow row in intersect)

{

Console.WriteLine("ID: {0} Name: {1}",

row.Field(0), row.Field(1));

}

IEnumerable except = result1.Except(result2);

// Enumerate the results.

Console.WriteLine("\nResults from except");

foreach (DataRow row in except)

{

Console.WriteLine("ID: {0} Name: {1}",

row.Field(0), row.Field(1));

}

}

// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter.");

Console.ReadLine();

}

}

}



476



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



Running the sample program gives the following results:

Results from first LINQ query

ID: 1 Name: Eastern

ID: 2 Name: Western



Results from second LINQ query

ID: 1 Name: Eastern

ID: 3 Name: Northern



Results from union

ID: 1 Name: Eastern

ID: 2 Name: Western

ID: 3 Name: Northern



Results from intersect

ID: 1 Name: Eastern



Results from except

ID: 2 Name: Western



Main method complete. Press Enter.



477



www.it-ebooks.info



www.it-ebooks.info



C H A P T E R 10

■■■



Networking

The Microsoft .NET Framework includes a full set of classes for network programming. These classes

support low-level network programming tasks like querying the state of network interfaces and socketbased programming with Transmission Control Protocol/Internet Protocol (TCP/IP) to higher-level

tasks like downloading files and HTML pages from the Web over Hypertext Transfer Protocol (HTTP).

You can even build fully distributed applications using distributed objects or service-oriented

approaches.

Included in the release of .NET Framework 3.0 was Windows Communication Foundation (WCF), a

unified programming model for building service-oriented applications. Although earlier technologies

are still available, WCF is generally seen as a replacement for technologies like .NET Remoting and

ASP.NET Web Services, and also provides a flexible unified interface through which to access many other

types of distributed communications, like message queues.

The recipes in this chapter describe how to do the following:





Obtain configuration and network statistic information about the network

interfaces on a computer as well as detect when network configuration changes

occur (recipes 10-1 and 10-2)







Download files from File Transfer Protocol (FTP) and HTTP servers (recipes 10-3,

10-4, and 10-6)







Respond to HTTP requests from within your application (recipe 10-5)







Send e-mail messages with attachments using Simple Mail Transfer Protocol

(SMTP) (recipe 10-7)







Use the Domain Name System (DNS) to resolve a host name into an Internet

Protocol (IP) address (recipe 10-8)







Ping an IP address to determine whether it is accessible and calculate round-trip

communication speeds by sending it an Internet Control Message Protocol

(ICMP) Echo request (recipe 10-9)







Communicate between programs through the direct use of TCP in both

synchronous and asynchronous communication models (recipes 10-10 and 10-11)







Communicate using User Datagram Protocol (UDP) datagrams where

connection-oriented and reliable TCP represents unnecessary overhead (recipe

10-12)



479



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING







Create a SOAP-based web service (recipe 10-13)







Generate a WCF service proxy dynamically (recipe 10-14)







Parse the contents of an Atom or RSS feed (recipe 10-15)







Manipulate uniform resource locators (URIs) (recipe 10-16)



■ Tip A number of the recipes in this chapter include a client and a server component that must both be running

for the recipe to work correctly. Where this is the case, the client and server code are contained in separate

projects. To run these recipes from within Visual Studio, set the server project as the startup project and run it

normally. Once the server is running, right-click the client project in Solution Explorer, click Debug on the context

menu, and then click “Start new instance.”



10-1. Obtain Information About the Local Network Interface

Problem

You need to obtain information about the network adapters and network configuration of the local

machine.



Solution

Call the static method GetAllNetworkInterfaces of the System.Net.NetworkInformation.

NetworkInterface class to get an array of objects derived from the abstract class NetworkInterface.

Each object represents a network interface available on the local machine. Use the members of each

NetworkInterface object to retrieve configuration information and network statistics for that interface.



How It Works

The System.Net.NetworkInformation namespace provides easy access to information about network

configuration and statistics. The primary means of retrieving network information are the properties

and methods of the NetworkInterface class. You do not instantiate NetworkInterface objects directly.

Instead, you call the static method NetworkInterface.GetAllNetworkInterfaces, which returns an array

of NetworkInterface objects. Each object represents a single network interface on the local machine. You

can then obtain network information and statistics about the interface using the NetworkInterface

members described in Table 10-1.



480



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING



■ Tip The System.Net.NetworkInformation.IPGlobalProperties class also provides access to useful

information about the network configuration of the local computer.



Table 10-1. Members of the NetworkInterface Class



Member



Description



Properties

Description



Gets a string that provides a general description of the interface.



Id



Gets a string that contains the identifier of the interface.



IsReceiveOnly



Gets a bool indicating whether the interface can only receive or can both send

and receive data.



Name



Gets a string containing the name of the interface.



NetworkInterfaceType



Gets a value from the System.Net.NetworkInformation.NetworkInterfaceType

enumeration that identifies the type of interface. Common values include

Ethernet, FastEthernetT, and Loopback.



OperationalStatus



Gets a value from the System.Net.NetworkInformation.OperationalStatus

enumeration that identifies the status of the interface. Common values include

Down and Up.



Speed



Gets a long that identifies the speed (in bits per second) of the interface as

reported by the adapter, not based on dynamic calculation.



SupportsMulticast



Gets a bool indicating whether the interface is enabled to receive multicast

packets.



Methods

GetIPProperties



Returns a System.Net.NetworkInformation.IPInterfaceProperties object that

provides access to the TCP/IP configuration information for the interface.

Properties of the IPInterfaceProperties object provide access to WINS, DNS,

gateway, and IP address configuration.



481



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

9-16. Compare LINQ DataSet Results

Tải bản đầy đủ ngay(0 tr)

×