What’s the Where for?

Asked

Viewed 391 times

0

I’ve seen it in several C# codes Where, but I didn’t understand about him.

  • What is algumacoisa.where() in the C#?
  • When should I last?
  • What good is?
  • 3

    Related or duplicated https://answall.com/q/125811/101

2 answers

7


You have a collection of numbers.

List<int> numeros = new List<int>
{
   1,2,3,4,5
}

You want a new collection with only even numbers from your otiginal list

var numPares = numeros.Where(x => x % 2 == 0).ToList();

The clause Where works as a filter for collections, in it you pass your criterion to filter a collection and receive a new collection filtered from the original collection.

See working on . NET Fiddle

Example with non-priminal type:

In the above example, I worked with a list of int (primitive type), what if it was a list of a class I created? Like a list of Pessoas?

public class Pessoa
{
   public string Nome { get; set; }
   public int Idade { get; set; }
}

Assuming I have a populated list:

var pessoas = new list<Pessoa>();
// Popula a lista com algumas pessoas...

Let’s filter:

// Pessoas Idosas
var pessoasIdosas = pessoas.Where(x => x.Idade > 60).ToList();

// Pessoas Idosas cujo nome começa com a letra "A"
var pessoasIdosasComNomeComecaLetraA = pessoas.Where(x => x.Idade > 60 && x.Nome.StartsWith("A")).ToList();

See working on . NET Fiddle

The fact that the list is typed (strongly typed) allows us to access the generic collection type properties (in the case of the example, the name and age) to perform filtering, this gives a very great power and efficiency for the code.

5

Where is a conditional clause Example: Return first car where the model is 'GOL', you can do a search on Lambda and Linq to understand more about these types of conditions.

List<Carro> carros = new List<Carro>();
carros.Where(x=>x.Modelo == "GOL").FirstOrDefault();
  • 1

    Tip: carros.FirstOrDefault(x => x.Modelo == "GOL"); is much less prolix.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.