Search item in a list using LINQ

Asked

Viewed 3,355 times

7

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

Ex: list all names from the list that start with 'JOAO%'

  • 1

    puts a toList() at the end

  • That’s right. I got it sorted ^^

  • 2

    Please try not to edit your questions by changing their scope. Especially when I have answers already, it invalidates the existing answers. If this happens again, you can open a new question and link this one from here, so it’s easier to keep things organized.

  • Okay, I didn’t know that.

2 answers

8


Of course. Using the method Where of LINQ. It is applicable in any enumerable collection (that implements IEnumerable).

Assuming you have a list of the kind string.

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

Suppose you have a list of a type and want to filter by 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 on dotNetFiddle.


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

  • I’m wearing it like this: var filtrado = listaCid.Where(x => x.descricao.StartsWith(txtBusca.Text)); gridCid.DataSource = filtrado; but the datagrid is not getting the result. I am doing wrong?

  • I can’t tell if my collection is Ienumerable. how do I know?

  • 1

    There’s no way I know. The problem could be anywhere. The list filtrado have any items? About "don’t know if the collection is IEnumerable" obviously she is, otherwise you wouldn’t even have the option of applying a Where.

  • I got it. I was missing by . Tolist at the end. Hug ^^

  • Great, good luck to you.

6

An alternative is also to use the query syntax from Linq, it is 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);

Exit:

Name: JOAO

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

See working here.

  • how do I assign the result to a dataGridView?

  • 1

    @Italorodrigo The problem is that you do not know how to update Datagrid. You have already checked the list filtrado have any items? Do you know how to change the Datasource of a Datagrid? It seems to me that the problem is just this.

  • really, I’m still new to VS, but I’m making some adaptations here to see if it works. Can you give me a tip?

  • 1

    Can, open a question and put the code that you are using to do this update so I can see. @Italorodrigo

  • I managed to fix it. thanks for your help

Browser other questions tagged

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