Last active
August 29, 2015 14:25
-
-
Save Fhernd/8eee9ef7e8185e21dc0e to your computer and use it in GitHub Desktop.
Uso de expresiones LINQ para crear expresiones de selección.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// OrtizOL - xCSw - http://ortizol.blogspot.com | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Recetas.CSharp.R0525 | |
{ | |
internal class Fruta | |
{ | |
public Fruta(string nombre, string color) | |
{ | |
Nombre = nombre; | |
Color = color; | |
} | |
public string Nombre | |
{ | |
get; | |
set; | |
} | |
public string Color | |
{ | |
get; | |
set; | |
} | |
} | |
internal class FrutaLinq | |
{ | |
public static void Main() | |
{ | |
// Creación de la colección con objetos Fruta: | |
List<Fruta> frutas = new List<Fruta>(){ | |
new Fruta("pera", "verde"), | |
new Fruta("mora", "rojo"), | |
new Fruta("cereza", "rojo"), | |
new Fruta("mango", "amarillo"), | |
new Fruta("banano", "amarillo"), | |
new Fruta("naranja", "naranaja"), | |
new Fruta("tomate", "rojo"), | |
new Fruta("melón", "amarillo"), | |
new Fruta("manzana", "verde") | |
}; | |
// Seleccionamos los nombres de las frutas que no son rojas, y | |
// que su primera letra es distinta de `p`: | |
IEnumerable<string> resultado = from fruta in frutas where fruta.Color != "rojo" | |
&& fruta.Nombre[0] != 'p' orderby fruta.Nombre | |
select fruta.Nombre; | |
// Visualización de resultados: | |
Console.WriteLine("\nConsulta usando expresiones estándar:"); | |
foreach(string nombre in resultado) | |
{ | |
Console.WriteLine("\tResultado: {0}.", nombre); | |
} | |
// Ahora usamos expresiones lambda para la misma consulta: | |
resultado = frutas.Where(fruta => fruta.Color != "rojo" && fruta.Nombre[0] != 'p'). | |
OrderBy(fruta => fruta.Nombre).Select(fruta => fruta.Nombre); | |
// Visualización de resultados: | |
Console.WriteLine("\nConsulta usando expresiones lambda:"); | |
foreach(string nombre in resultado) | |
{ | |
Console.WriteLine("\tResultado: {0}.", nombre); | |
} | |
Console.WriteLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment