Use of "Contains" in search expression

1

I have a string _Users of type List , it contains several lines.

Each line consists of an integer and a comma-separated string (usually just a string): ID (numbers only), name (letters and numbers ).

What I'm trying to do is find in which line the ID is located.

If I want to find the index of ID 1, the Contains() function will return the first line that contains "1", this will disturb if there is a named user, for example: "joao123".

int i = _Users.FindIndex(a => a.Contains(UserID.ToString()));

var dados = _Users[i];

string[] dado = dados.Split(',');
    
asked by anonymous 23.11.2018 / 21:44

3 answers

1

As I understand your question, you need to accurately capture the user with " id " equal to UserID .

In this way you do not need to compare using Contains , you can break the user's string with the comma using the Split() method.

var userId = 1;
var users = new [] { "1,Joao", "2,Marcos", "3,Joaquim123", "31,Jonas" };

// Faça assim para obter o usuário com exatamente o "id" = userId
var usuario = users.First(u => u.Split(',')[0] == userId.ToString());

// Faça isso para obter OS USUÁRIOS onde o "id" CONTENHA userId
var usuarios = users.Where(u => u.Split(',')[0].Contains(userId.ToString()));

Console.WriteLine($"Usuário com Id = {userId}");
Console.WriteLine($"\t{usuario}");

Console.WriteLine($"\n\nUsuário onde o Id contém {userId}");
foreach(var u in usuarios)
    Console.WriteLine($"\t{u}");

See working in .NET Fiddle     

23.11.2018 / 22:02
1

Use LINQ. I do not know if you want to get id or nome , I've done both:

using static System.Console;
using System.Collections.Generic;
using System.Linq;

public class Program {
    public static void Main() {
        var lista = new List<string> { "1,Joao",
            "2,Maria",
            "3,José1" };
        var nome = lista.Select(x => x.Split(',')).SingleOrDefault(a => a[1].Contains("1"));
        var id = lista.Select(x => x.Split(',')).SingleOrDefault(a => a[0].Contains("1"));
        WriteLine(nome[1]);
        WriteLine(id[1]);
    }
}

See running on .NET Fiddle . And no Coding Ground . Also I put it in GitHub for future reference .

You need to first isolate what is causing noise, so the Split() must occur before, and the search should occur only in the name, then it returns the item already splited . p>     

23.11.2018 / 22:03
0

It would be easier if you just typed one of these lines as an example.

If it looks like 1, Funaldo de Tal , you could use StartsWith instead of Contains , so if the ID is not found at the beginning, the comparison will return false .

int i = _Users.FindIndex(a => a.StartsWith(UserID.ToString()));

    
23.11.2018 / 22:00