<< Click to Display Table of Contents >> Linq |
![]() ![]() ![]() |
Linq com arrays
void ComLinq()
{
// LINQ em Arrays - modo mais rápido que List<int>
int[] numero = { 7, 2, 9, 0, 3, 1, 2, 6, 8 };
var res = from n in numero
where n < 7
orderby n
select n;
// mostra na tela
foreach (int num in res)
Console.WriteLine(num.ToString());
}
static void ComList()
{
// este modo é mais lento de todos
List<int> lista = new List<int>();
foreach (int i in numero)
if (i < 7)
lista.Add(i);
lista.Sort();
}
void ComLinqDistintos()
{
int[] numero = { 7, 2, 9, 0, 3, 1, 2, 3, 4, 2, 1, 2, 6, 8 };
var res = (from n in numero
orderby n
select n).Distinct();
// mostra na tela
foreach (int num in res)
Console.WriteLine(num.ToString());
}
void ComExpressaoLambda()
{
// LINQ em Arrays com Lambda - é mais rápido que Linq com where no corpo
int[] numero = { 7, 2, 9, 0, 3, 1, 2, 6, 8 };
var res = (from n in numero orderby n select n).Where(n => n < 7);
// mostra na tela
foreach (int num in res)
Console.WriteLine(num.ToString());
}
Concatenando strings de uma lista com Linq
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Cliente
{
public string Nome { get; set; }
public string Estado { get; set; }
public override string ToString()
{
return this.Nome;
}
}
class Program
{
static void Main(string[] args)
{
List<Cliente> lista = new List<Cliente>();
lista.Add(new Cliente() { Nome="Junior", Estado="SC" });
lista.Add(new Cliente() { Nome="Maria", Estado="RS" });
lista.Add(new Cliente() { Nome="João", Estado="RS" });
lista.Add(new Cliente() { Nome="Érica", Estado="SC" });
lista.Add(new Cliente() { Nome="Amanda", Estado="PR" });
lista.Add(new Cliente() { Nome = "Luke", Estado = "SC" });
string resultado = string.Concat((from u in lista where u.Estado == "SC" select u + ", "));
Console.WriteLine(resultado); // saída: "Junior, Érica, Luke,"
Console.ReadLine();
}
}
}