I have seen in several C # codes Where , but I did not understand about it.
- What is
algumacoisa.where()
in C #? - When should I use it?
- What's the use?
I have seen in several C # codes Where , but I did not understand about it.
algumacoisa.where()
in C #? You have a collection of numbers.
List<int> numeros = new List<int>
{
1,2,3,4,5
}
You want a new collection with just the even numbers from your otiginal list
var numPares = numeros.Where(x => x % 2 == 0).ToList();
The Where
clause works as a filter for collections, in it you pass your criteria to filter a collection and receive a new filtered collection from the original collection.
Example with non-primitive type:
In the example above, I worked with a list of int
(primitive type), and if it was a list of a class I created? Type 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();
The fact that the typed list (strongly typed) allows us to access the generic collection type properties (in the example case, name and age) to filter, this gives a very powerful power and efficiency for the code.
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();