Busca Online:

 
Seja bem vindo(a) Visitante, você não está logado deseja logar
no portal para participar de serviços e promoções ? clique aqui.


No caso de perder a senha, acesse aqui e receba por e-mail.
Deseja entrar em contato conosco, acesse aqui e mande-nos um e-mail.

Exemplos de Queries Linq

por Mauricio Junior em 1/1/2011 0

Exemplos de Queries utilizando o Linq

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<asp:ScriptManager ID="ScriptManager1" runat="server" />

<div>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>

<asp:ListBox ID="lstOption" runat="server" AutoPostBack="True"

onselectedindexchanged="lstOption_SelectedIndexChanged" Height="165px"

Width="351px">

<asp:ListItem Value="Hello">Hello Linq</asp:ListItem>

<asp:ListItem Value="Products">Query Products</asp:ListItem>

<asp:ListItem Value="Combine">Combine Where() and Select() for common queries</asp:ListItem>

<asp:ListItem Value="Where">Where</asp:ListItem>

<asp:ListItem Value="XML">XML</asp:ListItem>

</asp:ListBox>

<br />

<br />

<asp:Label ID="lblLinq" runat="server"></asp:Label>

<br />

<br />

<asp:Label ID="lblQuery" runat="server"></asp:Label>

<br />

<br />

<asp:GridView ID="gvwResults" runat="server">

</asp:GridView>

</ContentTemplate>

</asp:UpdatePanel>

</div>

</form>

</body>

</html>

 

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Collections;

using System.Collections.Generic;

using System.Linq;

using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page

{

NorthwindDataContext db = new NorthwindDataContext();

protected void Page_Load(object sender, EventArgs e)

{

}

protected void lstOption_SelectedIndexChanged(object sender, EventArgs e)

{

lblQuery.Text = String.Empty;

lblLinq.Text = String.Empty;

SelectLinq();

}

private void SelectLinq()

{

string strOption = lstOption.SelectedValue;

switch (strOption)

{

case "Hello":

Hello();

break;

case "Products":

Products();

break;

case "Combine":

Combine();

break;

case "Where":

Where();

break;

case "XML":

XML();

break;

default:

break;

}

}

private void Hello()

{

string[] greetings = { "hello world", "hello LINQ", "hello ASPNETi" };

 

//Coleção

IEnumerable<string> q = from s in greetings

where s.EndsWith("LINQ")

select s;

lblLinq.Text = "string[] greetings = { \"hello world\", \"hello LINQ\", \"hello ASPNETi\" };";

lblQuery.Text = "IEnumerable&lt;string&gt; q = from s in greetings <br> where s.EndsWith(\"LINQ\") <br> select s";

gvwResults.DataSource = q;

gvwResults.DataBind();

}

 

private void Combine()

{

// Combine Where() and Select() for common queries

IQueryable<string> q = db.Customers.Where(c => c.City == "London").Select(c => c.ContactName);

lblLinq.Text = q.ToString();

string strLinq = "Queryable&lt;string&gt; q = db.Customers.Where(c => c.City == \"London\").Select(c => c.ContactName);";

lblQuery.Text = strLinq;

gvwResults.DataSource = q;

gvwResults.DataBind();

}

 

 

private void Products()

{

IQueryable<Product> q = from p in db.Products

where p.Category.CategoryName == "Beverages"

select p;

lblLinq.Text = q.ToString();

string strLinq = "IQueryable&lt;Product&gt; q = from p in db.Products <br> where p.Category.CategoryName == \"Beverages\" <br>select p;";

lblQuery.Text = strLinq;

gvwResults.DataSource = q;

gvwResults.DataBind();

}

 

private void Where()

{

IQueryable<Product> q = from p in db.Products

where p.UnitsInStock == 0

select p;

lblLinq.Text = q.ToString();

string strLinq = "IQueryable&lt;Product&gt; q = from p in db.Products where p.UnitsInStock == 0 select p;";

lblQuery.Text = strLinq;

gvwResults.DataSource = q;

gvwResults.DataBind();

}

 

private void XML()

{

XElement books = XElement.Parse(

@"<books>

<book>

<title>Pro LINQ: Language Integrated Query in C# 2008</title>

<author>Joe Rattz</author>

</book>

<book>

<title>Pro WF: Windows Workflow in .NET 3.0</title>

<author>Bruce Bukovics</author>

</book>

<book>

<title>Pro C# 2005 and the .NET 2.0 Platform, Third Edition</title>

<author>Andrew Troelsen</author>

</book>

</books>");

var q =

from book in books.Elements("book")

where (string)book.Element("author") == "Joe Rattz"

select new { Title = book.Element("title").Value, Author = book.Element("author").Value };

 

lblQuery.Text = "var q = <br> from book in books.Elements(\"book\") <br> where (string)book.Element(\"author\") == \"Joe Rattz\" <br> select new { Title = book.Element(\"title\").Value, Author = book.Element(\"author\").Value };";

gvwResults.DataSource = q;

gvwResults.DataBind();

}

 

}

 

Fabio Galante Mans

fabio@netitc.com.br - Hospedagem para desenvolvedores

Baixar fonte

voltar   comente  subir

Download Copy





 
Mauricio Junior Formado pela Faculdade Anhanguera, Especialista pela FGV (Fundação Getúlio Vargas), Pós-Graduação em Docência Superior e cursando Mestrado na UNB Engenharia Elétrica; .
Tenho 29 anos e possuo sete livros publicados pela editora Ciência Moderna. Sou Certificado Microsoft MCP, MCAD e MVP, faço parte da comunidade ASPNETI.COM, ECODE10.COM, onde publico artigos, vídeos, ebooks e livros Publico artigos, vídeos e podcast em outras comunidades. Trabalho como Analista de Sistemas / Desenvolvedor na empresa ATP S/A. Blog: blog.mauriciojunior.org, Site pessoal www.mauriciojunior.org



Comentários:


Comente (dê sua opinião):

Comentário:
Código Imagem:  (digite o código da imagem respeitando maiúsculo e minúsculo)

Favor digitar o código da imagem para cadastramento.

 

Outros Artigos do Autor

Vídeo - Conecte
Fazer Log, precisa ou não precisa?
Armazenando Dados no ViewState Parte II
CES em Las Vegas
Tata Motors (Grupo TCS)
As várias mensagens do Sistema Operacional
Vídeo - Mostrando um sistema com pocket pc
Você tem boa postura no trabalho?
Gerando word com Visual Studio.NET 2005
Evento BrasilDotNet 2008
Vídeo Sobre Atributes e String Builder com Visual Studio .NET 2005
Trabalhando bem com o “using”
Limpando Cache do Brownser
Lendo Arquivo txt usando Visual Studio.NET 2005
Sistema iGas - Controle de Gasolina
Conhecendo o controle Wizard ASP.NET 2.0
Windows 7 funciona até no Mac
Sistema de Login em ASP – Parte VII (Utilizando três camadas)
Finanças para os filhos
Ebook: Aprendendo Desenvolver WebServices
Criando menu dinâmico com C#.NET (Passo 2) - Com diferenciação de usuário
Método para ordenar DataTable
Importar projetos antigos para o Visual Studio 2010
Adicionando Menu no DataGridView
Resources como padrão de mensagens
Misturando dados
ASP.MENU com Compatibilidade
Criando, utilizando e agendando sistema de backup
Sistema de Login – Parte IV
Desktop Linux Ubuntu
Resources e Internacionalização usando Visual Studio.NET 2005 - Parte III
Focus()
Criando Sections Customizados
SmartNavigation – 1.0 e 1.1 MaintainScroll PositionOn Postback – 2.0
GridView Parte II




eCode10 Magazine 4 Edição

Baixe a sua sem pagar nada, basta apenas ter um cadastro na comunidade aspneti.com ou ser usuário do ecode10.com.



Edições anteriores
LAYERDEV

Notícias *

Visão do Futuro - Day of Glass 2

Futuro próximo pode chegar cedo?...

Lenovo de 14 polegadas IdeaPad

Veja o novo notebook Lenovo IdeaPad...

Windows 8 Store

Channel9 publica um vídeo da Windows Store...

Sony Vaio série Z

Novo Vaio Ultrabook? ou não Ultrabook?...

Samsung quer comprar RIM

Imagine se juntar as duas companhias...

Surface 2.0 mostrado

Novo Surface é mostrado de forma incrível...

Skype Tablet

Será que esse skype tablet pega mesmo?...

Lenovo e o seu novo Ultrabook

Ultrabook chega também pela Lenovo...

Promoções de livros móveis .NET

Baixa agora o seu e aprenda a programar....




NETITC