Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
223 changes: 223 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
# Created by https://www.toptal.com/developers/gitignore/api/ruby,jekyll,jetbrains+all,rails
# Edit at https://www.toptal.com/developers/gitignore?templates=ruby,jekyll,jetbrains+all,rails

### Jekyll ###
_site/
.sass-cache/
.jekyll-cache/
.jekyll-metadata
# Ignore folders generated by Bundler
.bundle/
vendor/

### JetBrains+all ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# AWS User-specific
.idea/**/aws.xml

# Generated files
.idea/**/contentModel.xml

# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml

# Gradle
.idea/**/gradle.xml
.idea/**/libraries

# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr

# CMake
cmake-build-*/

# Mongo Explorer plugin
.idea/**/mongoSettings.xml

# File-based project format
*.iws

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# SonarLint plugin
.idea/sonarlint/

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

# Editor-based Rest Client
.idea/httpRequests

# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

### JetBrains+all Patch ###
# Ignore everything but code style settings and run configurations
# that are supposed to be shared within teams.

.idea/*

!.idea/codeStyles
!.idea/runConfigurations

### Rails ###
*.rbc
capybara-*.html
.rspec
/db/*.sqlite3
/db/*.sqlite3-journal
/db/*.sqlite3-[0-9]*
/public/system
/coverage/
/spec/tmp
*.orig
rerun.txt
pickle-email-*.html

# Ignore all logfiles and tempfiles.
/log/*
/tmp/*
!/log/.keep
!/tmp/.keep

# TODO Comment out this rule if you are OK with secrets being uploaded to the repo
config/initializers/secret_token.rb
config/master.key

# Only include if you have production secrets in this file, which is no longer a Rails default
# config/secrets.yml

# dotenv, dotenv-rails
# TODO Comment out these rules if environment variables can be committed
.env
.env*.local

## Environment normalization:
/.bundle
/vendor/bundle

# these should all be checked in to normalize the environment:
# Gemfile.lock, .ruby-version, .ruby-gemset

# unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
.rvmrc

# if using bower-rails ignore default bower_components path bower.json files
/vendor/assets/bower_components
*.bowerrc
bower.json

# Ignore pow environment settings
.powenv

# Ignore Byebug command history file.
.byebug_history

# Ignore node_modules
node_modules/

# Ignore precompiled javascript packs
/public/packs
/public/packs-test
/public/assets

# Ignore yarn files
/yarn-error.log
yarn-debug.log*
.yarn-integrity

# Ignore uploaded files in development
/storage/*
!/storage/.keep
/public/uploads

### Ruby ###
*.gem
/.config
/InstalledFiles
/pkg/
/spec/reports/
/spec/examples.txt
/test/tmp/
/test/version_tmp/
/tmp/

# Used by dotenv library to load environment variables.
# .env

# Ignore Byebug command history file.

## Specific to RubyMotion:
.dat*
.repl_history
build/
*.bridgesupport
build-iPhoneOS/
build-iPhoneSimulator/

## Specific to RubyMotion (use of CocoaPods):
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
# vendor/Pods/

## Documentation cache and generated files:
/.yardoc/
/_yardoc/
/doc/
/rdoc/

/.bundle/
/lib/bundler/man/

# for a library or gem, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# Gemfile.lock
# .ruby-version
# .ruby-gemset

# unless supporting rvm < 1.11.0 or doing something fancy, ignore this:

# Used by RuboCop. Remote config files pulled in from inherit_from directive.
# .rubocop-https?--*

# End of https://www.toptal.com/developers/gitignore/api/ruby,jekyll,jetbrains+all,rails
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,4 @@ bundle exec jekyll serve

- [Jekyll • Simple, blog-aware, static sites](https://jekyllrb.com/)

-


140 changes: 140 additions & 0 deletions _posts/2024-09-18-aprender-a-programar-em-csharp-parte-5.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
---
title: 'Aprender a programar em C# – Parte 5'
date: Thu, 18 Sep 2024 19:30:00 +0000
draft: false
tags: ['Aprender a programar em C#', 'C Sharp', 'C#','linq', 'lambda', 'Conceitos básicos', 'Iniciante', 'Visual Studio']
---
Na continuidade da nossa série sobre programação em C#, chegamos a um tema muito relevante e atual: LINQ (Language Integrated Query) e Expressões Lambda. Esses conceitos são fundamentais para quem deseja trabalhar com manipulação de dados de forma eficiente e expressiva. Neste artigo, vamos explorar o que são, como funcionam e como podemos utilizá-los em nossos projetos.

## 1. O que é LINQ?

LINQ é uma poderosa ferramenta que permite realizar consultas em coleções de dados de forma semelhante a consultas SQL, mas diretamente em C#. Com LINQ, você pode trabalhar com arrays, listas, bancos de dados e XML, entre outros, utilizando uma sintaxe clara e concisa.

### 1.1. Tipos de LINQ

Existem diferentes tipos de LINQ que podemos utilizar:

- **LINQ to Objects**: Permite realizar consultas em coleções em memória, como arrays e listas.
- **LINQ to SQL**: Permite realizar consultas em bancos de dados SQL Server.
- **LINQ to XML**: Permite realizar consultas em documentos XML.

## 2. Sintaxe do LINQ

A sintaxe do LINQ pode ser dividida em duas abordagens: **Sintaxe de Consulta** e **Sintaxe de Método**.

### 2.1. Sintaxe de Consulta

A sintaxe de consulta é semelhante à SQL e é bastante intuitiva. Veja um exemplo:

```csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
static void Main()
{
List<int> numeros = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var pares = from n in numeros
where n % 2 == 0
select n;
Console.WriteLine("Números pares:");
foreach (var numero in pares)
{
Console.WriteLine(numero);
}
}
}
```

### 2.2. Sintaxe de Método

A sintaxe de método utiliza métodos de extensão e é mais comum em cenários onde você precisa de operações mais complexas. Veja o mesmo exemplo utilizando a sintaxe de método:

```csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
static void Main()
{
List<int> numeros = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var pares = numeros.Where(n => n % 2 == 0);
Console.WriteLine("Números pares:");
foreach (var numero in pares)
{
Console.WriteLine(numero);
}
}
}
```

## 3. O que são Expressões Lambda?

Expressões Lambda são uma forma concisa de representar métodos anônimos. Elas são frequentemente usadas em LINQ para definir critérios de seleção, filtragem e transformação de dados.

### 3.1. Sintaxe de Expressões Lambda

A sintaxe básica de uma expressão lambda é:

```csharp
(parameters) => expression
```

Por exemplo, a expressão lambda `n => n % 2 == 0` recebe um parâmetro `n` e retorna um valor booleano indicando se `n` é par.

## 4. Usando LINQ e Expressões Lambda Juntos

Uma das grandes vantagens de LINQ é que ele permite o uso de expressões lambda para realizar operações de forma mais flexível. Veja um exemplo onde utilizamos LINQ com expressões lambda para filtrar e ordenar uma lista de objetos:

```csharp
using System;
using System.Collections.Generic;
using System.Linq;
class Pessoa
{
public string Nome { get; set; }
public int Idade { get; set; }
}

class Program
{
static void Main()
{
List<Pessoa> pessoas = new List<Pessoa>
{
new Pessoa { Nome = "Ana", Idade = 25 },
new Pessoa { Nome = "João", Idade = 30 },
new Pessoa { Nome = "Maria", Idade = 22 },
new Pessoa { Nome = "Pedro", Idade = 35 }
};

var pessoasFiltradas = pessoas
.Where(p => p.Idade > 25)
.OrderBy(p => p.Nome);

Console.WriteLine("Pessoas com mais de 25 anos:");

foreach (var pessoa in pessoasFiltradas)
{
Console.WriteLine($"{pessoa.Nome}, {pessoa.Idade} anos");
}
}
}
```

## 5. Conclusão

Neste artigo, introduzimos o LINQ e as expressões lambda, mostrando como essas ferramentas podem facilitar a manipulação de dados em C#. Com a prática, você poderá aplicar esses conceitos em seus projetos, tornando seu código mais limpo e eficiente.

No próximo artigo, continuaremos a explorar mais recursos do C# e como utilizá-los em aplicações do mundo real. Até lá, bons estudos e mãos à obra!

---

**Referências:**

- Documentação oficial do [LINQ](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/)
- Exemplos de [Expressões Lambda](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions)