C# - How to make a lambda filter with more than one field?

Asked

Viewed 957 times

5

My List:

public class Carro
{
   public int Ano;
   public double Valor;
}

List<Carro> Fiat = new List<Carro>();
Fiat.Add(new Carro {Ano = 2000, Valor = 5000 });
Fiat.Add(new Carro {Ano = 2000, Valor = 6000 });
Fiat.Add(new Carro {Ano = 2001, Valor = 7000 });
Fiat.Add(new Carro {Ano = 2002, Valor = 8000 });

How to make a filter in this list using lambda with more than one field?

  • It depends, which filter do you want to make? What filter? Show at least how you would do with a field to understand what you want.

2 answers

5


Create the function below and pass as parameters of the function the values you want to filter

    public List<Carro> Filtrar(List<Carro> lista, int Ano, double valor)
    {
        List<Carro> lstFiltrada = lista.Where(x => x.Ano == Ano && x.Valor == valor).ToList();
        return lstFiltrada;
    }

3

2003 cars down with value greater than 5000:

var lista = Fiat.Where(c => c.Ano <= 2003 & c.Valor > 5000);

Browser other questions tagged

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