Search list elements with partial strings

Asked

Viewed 310 times

6

I have a List<string> who receives the phone number of all the contacts on the phone, until there is no problem, but I want to perform some operations with the elements of that list, but I am with some problems.

An example of possible result:

lst = {"*126", "+55 3412345678", "12345678", "87654321", "3498761232"};

If you look, they’re all phone numbers, and I’ve stored them as a string to make it easier. Now I have to perform a search in this list, in all elements of the same (I do not know how many elements the list will have, because it depends on the user’s agenda).

Example: Typed user 123 in the textbox num and at the push of the button I search my list, the result should be:

+55 3412345678
12345678
3498761232

For if we look, they are the only elements of the list that contains the typed string (123).

So briefly, how to search in a list of indeterminate size, a string that can be anywhere in the element (start, middle, end, etc), the search should return at most 3 values, that is, if we have another element as for example 51234251, despite containing 123 it would not be returned, because we already found 3 elements with 123 before him.

Sorry if you got confused, it was the most detailed way I could report, in short, is to search a partial string in a list and return the first three elements that contain that string. But I could not accomplish such a task, I hope someone can help me, because it has been a lot of work and time to figure out how to take the number of contacts and store in the list.

1 answer

7


  • Uses the extension Enumerable.Where to filter the list by a predicate.
  • In this case, the predicate is: "the string must contain '123'". For this we can use String.Contains
  • Usa Enumerable.Take to get the first n result elements and discard the remaining.


var input = "123";

var filtered = list.Where(s => s.Contains(input))
                   .Take(3)
                   .ToList();

https://dotnetfiddle.net/R0tiro

  • 1

    It worked perfectly, I would never think it would be that simple, thank you!

  • Only by complementing this feature that dcastro used is the famous LINQ (Language Integrated Query or, in Portuguese, Integrated Query Language). To get an idea of the power of LINQ here at this address is an example of each of the features that LINQ offers: https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

Browser other questions tagged

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