Find list elements with partial strings

5

I have a List<string> that receives the phone number of all the contacts in the phone, until then without problem, but I want to perform operations with the elements of this list, but I have some problems.

An example of a possible result:

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

If you look, they are all phone numbers, and I stored it as a string, to make it easier. Now I have to perform a search in this list, in all elements of it (I do not know how much elements the list will have, because it depends on the user's schedule).

Example: User type 123 in the textbox num and when clicking the button I make the search in my list, the result should be:

+55 3412345678
12345678
3498761232

Well, if we look at it, they are the only elements in the list that contain the string entered ( 123 ).

So briefly, how to search a list of indeterminate length, a string that can be anywhere in the element (start, middle, end, etc.), the search should return a maximum of 3 values, ie if we have another element such as 51234251 , although it contains 123 it would not be returned, since we already found 3 elements with 123 before it.

Sorry if it was confusing, it was the most detailed way I could report, in short, is to look for a partial string in a list and return the first three elements that contain that string. But I was not able to do such a task, I hope someone can help me, because it was already a labor and time to figure out how to get the number of the contacts and store it on the list.

    
asked by anonymous 24.09.2015 / 06:38

1 answer

7
  • Uses the Enumerable.Where extension 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
  • Uses Enumerable.Take to get the first % with% elements of the result and discard the remaining elements.


var input = "123";

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

link

    
24.09.2015 / 10:00