Busca online em todo site:
Heroes

Seja bem vindo(a) Visitante, voc no est logado deseja logar
na comunidade ASPNETi.COM e participar de servios e promoes ? clique aqui.




Título do Artigo

Exemplos de Queries Linq


Data Publicação: 24/1/2008 11:17:36
Total de visualizações: 3854

comente
 


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



Total de visualizações: 3854
voltar   comente  subir

Autor:


Por:Fabio Galante Mans
Atualmente atua como desenvolvedor de aplicações .NET. Fundador do grupo ASPNETi.COM (www.aspneti.com), graduado em Análise de Sistemas. Site pessoal: www.mans.com.br


Comentários:


Comente (dê sua opinião): VOCÊ PRECISA ESTAR LOGADO

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

XmlDataSource
GridView - Valor total no footer
Como criptografar a string de conexão no Web.Config.
Vídeo aula explicando o que é o FreeTextBox e como utilizar em seu projetos ASP.NET.
Definindo o botão padrão.
Microsoft AdventureWorks Database
ASP .NET 2.0 Cross-Page Posting
Envio de e-mail através de formulário web
Como criar uma tabela dinâmica com ASP.NET
Exemplos de Queries Linq
Page.Header
Prepare o Sql Server para o VS 2005
Padrões de nomenclaturas
ASP.NET 2.0 - FileUpload
SmartNavigation – 1.0 e 1.1 MaintainScroll PositionOn Postback – 2.0
Cookies
Web Administration Tool
Tudo Sobre DataGrid - (ASP.NET e C#)
Customizando o Membership e Role Provider
Append Data Bound Items
Conhecendo o controle Wizard ASP.NET 2.0
CSS no VS 2003
Focus()
Perguntas Mais Freqüentes de ASP.NET
Label Server Control AccessKey
Utilizando o GridView e DetailsView
Membership
Como utilizar CSS no VS 2003

Publicidade:

[sumir] [aparecer]
NETITC




Informaes Online:

Usurios Online: 762
Artigos:  655
Vdeos:  47
PodCast's:  31
Frum:  3098
Empregos:  1223
Usurios Cadastrados: 5785

Categoria de Artigos

Vdeos

Enquete - D sua opinio

 Os podcasts tem sido proveitoso pra você?

 

Colaboradores

Foto Autor autor: Mauricio Junior   
publicou 380 artigo(s).
Foto Autor autor: Júlio Battisti   
publicou 51 artigo(s).
Foto Autor autor: Fabio Galante Mans   
publicou 28 artigo(s).
Foto Autor autor: Kleber Becerra   
publicou 10 artigo(s).
Foto Autor autor: Ramon Durães   
publicou 6 artigo(s).
Foto Autor autor: Ebenézer de Souza   
publicou 5 artigo(s).
Foto Autor autor: Fabio Aguiar   
publicou 4 artigo(s).
NETITC