5
How to use the ForEach()
of List
in the implementation below
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<Pessoa> pessoas = new List<Pessoa>();
pessoas.Add(new Pessoa(){Nome = "José" , Sexo = "M"});
pessoas.Add(new Pessoa(){Nome = "Pedro", Sexo = "M"});
pessoas.Add(new Pessoa(){Nome = "João" , Sexo = "M"});
pessoas.Add(new Pessoa(){Nome = "Maria", Sexo = "F"});
bool temMulher = new VerificaSeHaMulher(pessoas).Verifica();
}
}
class VerificaSeHaMulher
{
List<Pessoa> pessoas;
public VerificaSeHaMulher(List<Pessoa> pessoas)
{
this.pessoas = pessoas;
}
public bool Verifica()
{
foreach(Pessoa pessoa in pessoas)
if(pessoa.Sexo.Equals("F"))
return true;
return false;
}
}
class Pessoa
{
public string Nome;
public string Sexo;
}
In this case, I want to make the implementation of the method cleaner Verifica
.
Is there anything specific that you think is bad? It seems pretty simple. Is there a need to be a class? Nothing wrong with that, as long as you need it. Maybe you’re using a Strategy Pattern or variation of it somewhere. But if you’re using it by accident, you should simplify it. Otherwise I would only change the syntax of the comparison so as not to look like Java. Where lambda gets into that story?
– Maniero
Had put the lambda by ignorance. Adjusted
– Guilherme Silva
The confusion makes sense. See: http://answall.com/q/79894/101 and http://answall.com/q/22265/101 and http://answall.com/q/14212/101
– Maniero
One option to simplify code is the use of resharper is a paid component plus is good for this type of help. https://www.jetbrains.com/resharper/
– Marco Souza
@Guilhermesilva, I advise you to read "foreach" vs "foreach" and Where is List<T>. Foreach().
– Tobias Mesquita