Last active
June 10, 2021 23:06
-
-
Save robsonfaxas/75620fc5d6e44266749bdd81394f8002 to your computer and use it in GitHub Desktop.
[LinqToDataset - para consulta dataset] Consultar dados de um Dataset utilizando Linq #linq
This file contains hidden or 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
static void Main(string[] args) | |
{ | |
DataSet dsAdventure = PopularDataSet(); // metodo após o main | |
DataTable dtProduto = dsAdventure.Tables["Product"]; | |
IEnumerable<DataRow> produtos = | |
from p in dtProduto.AsEnumerable() | |
where p.Field<string>("Color") == "Black" // observe o campo Field<T> que faz a tipagem | |
orderby p.Field<string>("Name") descending | |
select p; | |
//Em sintaxe de método ficaria da seguinte forma: | |
//IEnumerable<DataRow> produtos = dtProduto.AsEnumerable().Where(p => p.Field<string>("Color") == "Black").OrderByDescending(p => p.Field<string>("Name")); | |
foreach (DataRow dr in produtos) | |
{ | |
Console.WriteLine("{0} \t- {1}", dr["ProductNumber"], dr["Name"]); | |
} | |
Console.ReadKey(); | |
} | |
static DataSet PopularDataSet() | |
{ | |
SqlConnection cn = new SqlConnection(); | |
cn.ConnectionString = @"Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=SSPI"; | |
SqlCommand cmd = new SqlCommand(); | |
cmd.Connection = cn; | |
cmd.CommandText = "SELECT * FROM Production.Product"; | |
SqlDataAdapter da = new SqlDataAdapter(); | |
da.SelectCommand = cmd; | |
DataSet ds = new DataSet(); | |
da.Fill(ds, "Product"); | |
return ds; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment