Skip to content

Instantly share code, notes, and snippets.

@robsonfaxas
Created June 10, 2021 23:09
Show Gist options
  • Save robsonfaxas/8ea9ea389492f0c19b69acaa5ca1a26f to your computer and use it in GitHub Desktop.
Save robsonfaxas/8ea9ea389492f0c19b69acaa5ca1a26f to your computer and use it in GitHub Desktop.
[LinqToDataset - Populando objetos] Populando objetos a partir de datasets com #linq
class Produto
{
public int Id { get; set; }
public string Nome { get; set; }
public string Numero { get; set; }
}
static void Main(string[] args)
{
dsAdventure dsAdventure = PopularDataSet();
dsAdventure.ProductDataTable dtProduto = dsAdventure.Product;
List<Produto> produtos =
(from p in dtProduto.AsEnumerable()
where !p.IsColorNull() && p.Color == "Black"
orderby p.Name descending
select new Produto
{
Id = p.ProductID,
Nome = p.Name,
Numero = p.ProductNumber
}).ToList();
//Em sintaxe de método ficaria da seguinte forma:
//List<Produto> produtos = dtProduto.AsEnumerable()
// .Where(p => !p.IsColorNull() && p.Color == "Black")
// .OrderByDescending(p => p.Field<string>("Name"))
// .Select(p => new Produto
// {
// Id = p.ProductID,
// Nome = p.Name,
// Numero = p.ProductNumber
// }).ToList();
foreach (Produto p in produtos)
{
Console.WriteLine("{0} \t- {1}", p.Numero, p.Nome);
}
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