C #y lambda

  • Rabid Dog
  • Web Master
  • Web Master
  • Avatar de Usuario
  • Registrado: May 21, 2004
  • Mensajes: 3229
  • Loc: South Africa
  • Status: Offline

Nota Abril 24th, 2011, 2:00 pm

Bueno, ha sido un tiempo y he estado trabajando con algunas cosas realmente interesantes últimamente.

Pensé que iba a compartir esta práctica tres veces al día poco de información para hacer su vida más fácil en. NET específicamente C #.

¿Cuántas veces has colocado en una lista en busca de propiedades de la clase correspondiente, y añadió que otra lista para mostrarlas? Bueno, yo sé lo he hecho paso a veces por lo que cuando empecé a usar expresiones LINQ y lambda Tengo mucha ilusión!

Ok, así sin más hacer una suelta.

Digamos que tenemos una clase base

Código: [ Select ]
public class Person{
 public String FirstName{get;set;}
 public String LastName{get;set;}
 public String Email{get;set;}
}
  1. public class Person{
  2.  public String FirstName{get;set;}
  3.  public String LastName{get;set;}
  4.  public String Email{get;set;}
  5. }


Ahora da un método que rellena una lista de objetos Person
Código: [ Select ]
var myList = new List<Person>();

for(int i = 0; i < 10; i++){
myList.Add(
 //Excuse the concatination, prefered method is String.Format
 new Person{FirstName = "Name [1]" + 1, LastName = "LastName " + [1], Email = "Email" + i + "@domain.com"};
)
}
  1. var myList = new List<Person>();
  2. for(int i = 0; i < 10; i++){
  3. myList.Add(
  4.  //Excuse the concatination, prefered method is String.Format
  5.  new Person{FirstName = "Name [1]" + 1, LastName = "LastName " + [1], Email = "Email" + i + "@domain.com"};
  6. )
  7. }


Ahora tenemos una lista de la Persona con 10 entradas. Ahora bien, si queríamos encontrar la entrada con el nombre "Nombre 1" usted tradicionalmente recorrer la lista hasta que acertaron el nombre. Algo como

Código: [ Select ]
var myPerson = null;
foreach(var person in myList){
 if(myList.FirstName.Equals("Name 1")){
  myPerson = person;
  break;
 }
}
  1. var myPerson = null;
  2. foreach(var person in myList){
  3.  if(myList.FirstName.Equals("Name 1")){
  4.   myPerson = person;
  5.   break;
  6.  }
  7. }


El hombre que puede ser molesto. Así que MS nos ha provisto de un práctico conjunto de método de extensión en la biblioteca de LINQ. Para incluir en tu CS de presentar simplemente la referencia del espacio de nombres System.Linq

Código: [ Select ]
using System.Linq;


Ahora, para lograr lo mismo que el bucle foreach que sólo tiene que ir
Código: [ Select ]
//The first or default method returns null if it doesn't find a match, First() will throw an exception if no
//matching objects are found
var myPerson = myList.FirstOrDefault(person => person.FirstName.Equals("Name 1"));
  1. //The first or default method returns null if it doesn't find a match, First() will throw an exception if no
  2. //matching objects are found
  3. var myPerson = myList.FirstOrDefault(person => person.FirstName.Equals("Name 1"));


Ahora que está limpio!
Podemos también las listas de consulta de la lista
Código: [ Select ]
//Obviously this will return all ten results but illustrates the purpose
var myNewList = myList.Where(person => person.FirstName.StartsWith("Name "));
  1. //Obviously this will return all ten results but illustrates the purpose
  2. var myNewList = myList.Where(person => person.FirstName.StartsWith("Name "));


Fresco ¿eh? Pero esto es sólo el principio! Digamos que agregar otra propiedad a otra.
Código: [ Select ]
public class Person{
 public String FirstName{get;set;}
 public String LastName{get;set;}
 public String Email{get;set;}
 public int Salary {get;set;} //yes I know, float float float -> keeping it simple
}
  1. public class Person{
  2.  public String FirstName{get;set;}
  3.  public String LastName{get;set;}
  4.  public String Email{get;set;}
  5.  public int Salary {get;set;} //yes I know, float float float -> keeping it simple
  6. }


y lo pueblan con
Código: [ Select ]
var myList = new List<Person>();
Random random = new Random();
int randomNumber = random.Next(0, 100);

for(int i = 0; i < 10; i++){
myList.Add(
 //Excuse the concatination, prefered method is String.Format
 var salary = random.Next() * 1;
 new Person{FirstName = "Name [1]" + 1, LastName = "LastName " + [1], Email = "Email" + i + "@domain.com", Salary = salary};
)
}
  1. var myList = new List<Person>();
  2. Random random = new Random();
  3. int randomNumber = random.Next(0, 100);
  4. for(int i = 0; i < 10; i++){
  5. myList.Add(
  6.  //Excuse the concatination, prefered method is String.Format
  7.  var salary = random.Next() * 1;
  8.  new Person{FirstName = "Name [1]" + 1, LastName = "LastName " + [1], Email = "Email" + i + "@domain.com", Salary = salary};
  9. )
  10. }


Y queremos encontrar el costo total de la Lista de Personas
Código: [ Select ]
var total = myList.Sum(person => person.Salary);

¿O queremos encontrar a la media de todos los salarios
Código: [ Select ]
var avg = myList.Avg(person => person.Salary);


Ahora no me importa quién eres, que es cool.It se extiende mucho más allá de eso, así que recomiendo echar un vistazo!

Para ver más información de
Lambda expresiones:
http://msdn.microsoft.com/en-us/library/bb397687.aspx

Linq
http://msdn.microsoft.com/en-us/netframework/aa904594

Disfrute!
Watch me grow
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Abril 24th, 2011, 2:00 pm

Publicar Información

  • Total de mensajes en este tema: 1 mensaje
  • Moderador: Tutorial Writers
  • Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 1 invitado
  • No puede abrir nuevos temas en este Foro
  • No puede responder a temas en este Foro
  • No puede editar sus mensajes en este Foro
  • No puede borrar sus mensajes en este Foro
  • No puede enviar adjuntos en este Foro
 
 

© 2011 Unmelted, LLC. Ozzu® es una marca registrada de Unmelted, LLC