Sei sulla pagina 1di 27

Ingeniera de Sistemas Programacin 3

Clase 4

Profesor David Lpez F.

ADO.NET

El ADO.NET es un conjunto de componentes del software que pueden ser usados por los programadores para acceder a datos y a servicios de datos. Es una parte de la biblioteca de clases base que estn incluidas en el Microsoft .NET Framework. Es comnmente usado por los programadores para acceder y para modificar los datos almacenados en un Sistema Gestor de Bases de Datos Relacionales, aunque tambin puede ser usado para acceder a datos en fuentes no relacionales. ADO.NET es a veces considerado como una evolucin de la tecnologa ActiveX Data Objects (ADO), pero fue cambiado tan extensivamente que puede ser concebido como un producto enteramente nuevo.

DataSet
string sConnectionString; sConnectionString = "Password=myPassword;User ID=myUserID;" + "Initial Catalog=pubs;" + "Data Source=(local)"; SqlConnection objConn = new SqlConnection(sConnectionString); objConn.Open();

SqlDataAdapter daAuthors = new SqlDataAdapter("Select * From Authors", objConn); DataSet dsPubs = new DataSet("Pubs"); daAuthors.FillSchema(dsPubs,SchemaType.Source, "Authors"); daAuthors.Fill(dsPubs,"Authors");
DataTable tblAuthors; tblAuthors = dsPubs.Tables["Authors"]; foreach (DataRow drCurrent in tblAuthors.Rows) { Console.WriteLine("{0} {1}", drCurrent["au_fname"].ToString(), drCurrent["au_lname"].ToString()); } objConn.Close();

DataTable
static DataTable GetTable() { // Here we create a DataTable with four columns. DataTable table = new DataTable(); table.Columns.Add("Weight", typeof(int)); table.Columns.Add("Name", typeof(string)); table.Columns.Add("Breed", typeof(string)); table.Columns.Add("Date", typeof(DateTime)); // Here we add five DataRows. table.Rows.Add(57, "Koko", "Shar Pei", DateTime.Now); table.Rows.Add(130, "Fido", "Bullmastiff", DateTime.Now); table.Rows.Add(92, "Alex", "Anatolian Shepherd Dog", DateTime.Now); table.Rows.Add(25, "Charles", "Cavalier King Charles Spaniel", DateTime.Now); table.Rows.Add(7, "Candy", "Yorkshire Terrier", DateTime.Now); return table; }

DataTable y DataRow static void Main() { // // Get the first row from the DataTable. // DataTable table = GetTable(); DataRow row = table.Rows[0]; Console.WriteLine(row["Breed"]); // // Get the last row in the DataTable. // DataRow last = table.Rows[table.Rows.Count - 1]; Console.WriteLine(last["Breed"]); }

DataRow
static void Main() { // // Get the first row and loop over its ItemArray. // DataTable table = GetTable(); DataRow row = table.Rows[0]; foreach (object item in row.ItemArray) { if (item is int) { Console.WriteLine("Int: {0}", item); } else if (item is string) { Console.WriteLine("String: {0}", item); } else if (item is DateTime) { Console.WriteLine("DateTime: {0}", item); } } }

DataRowCollection
// code is truncated for brevity;

DataRowCollection drcComputer = ds1.Tables["scsdComputer"].Rows; foreach (DataRow row in drcComputer) { // search for assetID from computer table in asset table string strrowSelect = "assetID = '" + strassetID + "'"; DataRow[] foundRows = ds1.Tables["asset"].Select(strrowSelect);
// if assetID does not exist in asset table, then add it if (foundRows.Length < 1) { // add new row DataRow newRow = ds1.Tables["asset"].NewRow(); newRow["assetID"] = strassetID; ds1.Tables["asset"].Rows.Add(newRow); } else { // NOTE: this is where I am having problems } }

ArrayList Implementa la interfaz IList mediante una matriz cuyo tamao aumenta dinmicamente segn se requiera.
No se garantiza que la matriz ArrayList est ordenada. Debe ordenar la matriz ArrayList antes de realizar operaciones (como BinarySearch) que requieren que la matriz ArrayList est ordenada. La capacidad de un objeto ArrayList es el nmero de elementos que puede contener el objeto ArrayList. La capacidad inicial predeterminada de un objeto ArrayList es 0. Conforme se agregan elementos a un objeto ArrayList, la capacidad aumenta automticamente segn lo requiera la reasignacin. Se puede disminuir la capacidad llamando al mtodo TrimToSize o estableciendo explcitamente la propiedad Capacity. Se puede obtener acceso a los elementos de esta coleccin utilizando un ndice entero. Los ndices de esta coleccin estn basados en cero.

ArrayList
using System; using System.Collections; public class SamplesArrayList { public static void Main() { ArrayList myAL = new ArrayList(); myAL.Add("Hello"); myAL.Add("World"); myAL.Add("!"); Console.WriteLine( "myAL" ); Console.WriteLine( " Count: {0}", myAL.Count ); Console.WriteLine( " Capacity: {0}", myAL.Capacity ); Console.Write( " Values:" ); PrintValues( myAL ); } public static void PrintValues( IEnumerable myList ) { foreach ( Object obj in myList ) Console.Write( " {0}", obj ); Console.WriteLine(); } }

List
Representa una lista fuertemente tipada de objetos a los que se puede obtener acceso por el ndice. Proporciona mtodos para buscar, ordenar y manipular listas.
using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(); list.Add(2); list.Add(3); list.Add(5); list.Add(7); //Limpiar los Elementos de la Lista. list.Clear(); } }

List
using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(); list.Add(2); list.Add(3); list.Add(7); foreach (int prime in list) // Loop through List with foreach { Console.WriteLine(prime); } for (int i = 0; i < list.Count; i++) // Loop through List with for { Console.WriteLine(list[i]); } } }

Insert en List
using System; using System.Collections.Generic; class Program { static void Main() { List<string> dogs = new List<string>(); // Example List dogs.Add("spaniel"); // Contains: spaniel dogs.Add("beagle"); // Contains: spaniel, beagle dogs.Insert(1, "dalmation"); // Contains: spaniel, dalmation, beagle foreach (string dog in dogs) // Display for verification { Console.WriteLine(dog); }

}
}

Obtener Rango del List


using System; using System.Collections.Generic; class Program { static void Main() { List<string> rivers = new List<string>(new string[] { "nile", "amazon", // River 2 "yangtze", // River 3 "mississippi", "yellow" }); // Get rivers 2 through 3 List<string> range = rivers.GetRange(1, 2); foreach (string river in range) { Console.WriteLine(river); } } }

Copiar Array a List


using System; using System.Collections.Generic; class Program { static void Main() { int[] arr = new int[3]; // New array with 3 elements arr[0] = 2; arr[1] = 3; arr[2] = 5; List<int> list = new List<int>(arr); // Copy to List Console.WriteLine(list.Count); // 3 elements in List } }

List<T>.BinarySearch (Mtodo) (T)


En el ejemplo de cdigo siguiente se muestran la sobrecarga del mtodo Sort() y la sobrecarga del mtodo BinarySearch(T). Se crea un objeto List<T> de cadenas y se rellena de cuatro cadenas, sin un orden concreto. La lista se muestra, se ordena y se vuelve a mostrar. A continuacin, se utiliza la sobrecarga del mtodo BinarySearch(T) para buscar dos cadenas que no estn en la lista y se usa el mtodo Insert para insertarlas. En cada caso, el valor que devuelve el mtodo BinarySearch(T) es negativo, puesto que las cadenas no estn en la lista. Al tomar el complemento bit a bit (el operador ~ en C# y Visual C++, Xor -1 en Visual Basic) de este nmero negativo se produce el ndice del primer elemento de la lista que es mayor que la cadena buscada y la insercin en esta posicin conserva el criterio de ordenacin. La segunda cadena buscada es mayor que cualquier elemento de la lista, de modo que la posicin de insercin es el final de la lista.

List<T>.BinarySearch (Mtodo) (T)


List<string> dinosaurs = new List<string>();

dinosaurs.Add("Pachycephalosaurus"); dinosaurs.Add("Amargasaurus"); dinosaurs.Add("Mamenchisaurus"); dinosaurs.Add("Deinonychus");


Console.WriteLine(); foreach(string dinosaur in dinosaurs) { Console.WriteLine(dinosaur); } //Pachycephalosaurus //Amargasaurus //Mamenchisaurus //Deinonychus

List<T>.BinarySearch (Mtodo) (T)


Console.WriteLine("\nSort"); dinosaurs.Sort(); Console.WriteLine(); foreach(string dinosaur in dinosaurs) { Console.WriteLine(dinosaur); } //Amargasaurus //Deinonychus //Mamenchisaurus //Pachycephalosaurus

List<T>.BinarySearch (Mtodo) (T)


Console.WriteLine("\nBinarySearch and Insert \"Coelophysis\":"); int index = dinosaurs.BinarySearch("Coelophysis"); if (index < 0) { dinosaurs.Insert(~index, "Coelophysis"); } Console.WriteLine(); foreach(string dinosaur in dinosaurs) { Console.WriteLine(dinosaur); } //Amargasaurus //Coelophysis //Deinonychus //Mamenchisaurus //Pachycephalosaurus

Hashtable
Representa una coleccin de pares de clave y valor organizados en funcin del cdigo hash de la clave.

Ejemplo
Hashtable openWith = new Hashtable(); openWith.Add("txt", "notepad.exe"); openWith.Add("bmp", "paint.exe"); openWith.Add("dib", "paint.exe"); openWith.Add("rtf", "wordpad.exe"); ICollection keyColl = openWith.Keys; Console.WriteLine(); foreach (string s in keyColl) { Console.WriteLine("Key = {0}", s); } //Key = rtf //Key = txt //Key = dib //Key = bmp

Hashtable
ICollection keyValue = openWith.Values; Console.WriteLine(); foreach (string s in keyValue) { Console.WriteLine("Value = {0}", s); } //Value = wordpad.exe //Value = notepad.exe //Value = paint.exe //Value = paint.exe foreach (DictionaryEntry de in openWith) { Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value); } //Key = rtf, Value = wordpad.exe //Key = txt, Value = notepad.exe //Key = dib, Value = paint.exe //Key = bmp, Value = paint.exe

Hashtable
if (!openWith.ContainsKey("doc")) { Console.WriteLine("Key \"doc\" is not found."); } //Key "doc" is not found. openWith["rtf"] = "winword.exe"; if (openWith.ContainsKey("rtf")) { openWith.Remove("rtf"); Console.WriteLine("Key \"rtf\" Eliminado."); } //Key "rtf" Eliminado. if (!openWith.ContainsKey("ht")) { openWith.Add("ht", "hypertrm.exe"); Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]); } //Value added for key = "ht": hypertrm.exe

Dictionary

Representa una coleccin de claves y valores.

Dictionary<string, string> openWith = new Dictionary<string, string>();

Copiar Dictionary a List


using System; using System.Collections.Generic; class Program { static void Main() { // Populate example Dictionary var dict = new Dictionary<int, bool>(); dict.Add(3, true); dict.Add(5, false);

// Get a List of all the Keys List<int> keys = new List<int>(dict.Keys); foreach (int key in keys) { Console.WriteLine(key); }
} }

SortedList
Representa una coleccin de pares de clave y valor ordenados por claves a los que se puede tener acceso por clave y por ndice. SortedList mantiene internamente dos matrices para almacenar los elementos de la lista; es decir, una matriz para las claves y otra para los valores asociados. Cada elemento es un par de clave y valor al que se puede obtener acceso como un objeto DictionaryEntry. La capacidad de SortedList es el nmero de elementos que SortedList puede contener. La capacidad inicial predeterminada de SortedList es 0. A medida que se agregan elementos a una coleccin SortedList, la capacidad aumenta automticamente segn lo requiera la reasignacin. La capacidad se puede disminuir si se llama al mtodo TrimToSize o si se establece explcitamente la propiedad Capacity. Los elementos de SortedList se ordenan por claves en funcin de una implementacin determinada de IComparer que se especifica al crear SortedList o de acuerdo con la implementacin de IComparable proporcionada por las propias claves. En cualquier caso, SortedList no admite claves duplicadas. La secuencia de ndices se basa en la secuencia de ordenacin. Cuando se agrega un elemento, se inserta en SortedList en el orden correcto y la indizacin se ajusta en consonancia. Cuando se quita un elemento, la indizacin tambin se ajusta en consonancia. Por lo tanto, el ndice de un par de clave y valor especfico puede cambiar a medida que se agregan o quitan elementos de la coleccin SortedList.

Las operaciones de SortedList suelen ser ms lentas que las operaciones de Hashtable debido a la ordenacin. Sin embargo, SortedList ofrece ms flexibilidad, ya que permite el acceso a los valores mediante las claves asociadas o mediante los ndices.

SortedList
SortedList mySL = new SortedList(); mySL.Add("First", "Hello"); mySL.Add("Second", "World"); mySL.Add("Third", "!");

Console.WriteLine("mySL"); Console.WriteLine(" Count: {0}", mySL.Count); Console.WriteLine(" Capacity: {0}", mySL.Capacity); Console.WriteLine(" Keys and Values:");
PrintKeysAndValues(mySL);

SortedList
public static void PrintKeysAndValues(SortedList myList) { Console.WriteLine("\t-KEY-\t-VALUE-"); for (int i = 0; i < myList.Count; i++) { Console.WriteLine("\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i)); } Console.WriteLine(); } //mySL // Count: 3 // Capacity: 16 // Keys and Values: // -KEY- -VALUE// First: Hello // Second: World // Third: !

Gracias por la Atencin!

Potrebbero piacerti anche