Find item in a list using LINQ

7

I have a list and I want to search it (as if it were a database). Is it possible?

Ex: list all list names starting with 'JOAO%'

    
asked by anonymous 19.01.2017 / 12:58

2 answers

8

Of course. Using the LINQ method Where . It is applicable to any enumerable collection (which implements IEnumerable ).

Assuming you have a list of type string .

var filtrado = lista.Where(str => str.StartsWith("JOAO")).ToList();

Assuming you have a list of one type and want to filter for some property.

using System;
using System.Collections.Generic;   
using System.Linq;

using static System.Console;

public class Program
{
    static List<Cliente> listaClientes = new List<Cliente>
    {
        new Cliente { Id = 1, Nome = "Joao Carlos" },   
        new Cliente { Id = 2, Nome = "Joao Paulo" },
        new Cliente { Id = 3, Nome = "Joao da Silva" },
        new Cliente { Id = 4, Nome = "Jéferson" },
        new Cliente { Id = 5, Nome = "Joaquim" },
        new Cliente { Id = 6, Nome = "Maria Joao" },
        new Cliente { Id = 7, Nome = "Jonathan" },
    };

    public static void Main()
    {
        var filtrado = listaClientes.Where(x => x.Nome.StartsWith("Joao")).ToList(); 

        foreach(var cliente in filtrado)
        {
            WriteLine($"{cliente.Nome}");   
        }
    }
}

public class Cliente
{
    public int Id { get; set; }
    public string Nome { get; set; }
}

See working at dotNetFiddle.

You can read this answer that talks about StartsWith , Contains , and EndsWith .

    
19.01.2017 / 13:00
6

An alternative is also to use Linq's syntax , it's a bit similar to Sql, see an example:

List<string> lista = new List<string>();
lista.Add("JOAO");
lista.Add("Maria");
lista.Add("LUCAS");

var nome = 
    (
        from n in lista 
        where n.Contains("JOAO") 
        select n
    ).FirstOrDefault();

Console.WriteLine("Nome: {0}", nome);

Output:

  

Name: JOAO

In the example above I used the method Contains() but you can replace it with StartsWith() , this way you will get what you want.

See working here .

    
19.01.2017 / 13:20