Skip to content

Instantly share code, notes, and snippets.

@luisdeol
Last active April 26, 2021 19:00
Show Gist options
  • Save luisdeol/070eecbf7c2a0d50438180813e117546 to your computer and use it in GitHub Desktop.
Save luisdeol/070eecbf7c2a0d50438180813e117546 to your computer and use it in GitHub Desktop.
Artigo LINQ #1: Utilizando todos os métodos
using System;
using System.Collections.Generic;
using System.Linq;
namespace ArtigoLinqParteUm
{
class Program
{
static void Main(string[] args)
{
var students = new List<Student>
{
new Student("Luis", 980),
new Student("Felipe", 650),
new Student("Dev", 340),
};
var luis = students.SingleOrDefault(s => s.Name == "Luis");
var richard = students.SingleOrDefault(s => s.Name == "Richard"); // Retorna null
// var richardException = students.Single(s => s.Name == "Richard"); // Lança InvalidOperationException
var firstWithOver600Grade = students.First(s => s.Grade > 600);
var firstWith1000Grade = students.FirstOrDefault(s => s.Grade == 1000); // Retorna null
// var firstWith1000GradeException = students.First(s => s.Grade == 1000); // Lança InvalidOperationException
var allStudentsOver500Grade = students.Where(s => s.Grade > 500);
foreach (var student in allStudentsOver500Grade)
{
Console.WriteLine($"Name: {student.Name}, Grade: {student.Grade}");
// Imprime duas linhas
// Name: Luis, Grade: 980
// Name: Felipe, Grade: 650
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment