Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindAll search question

Tags:

c#

list

findall

I have a list like this:

item.Add("a");
item.Add("as");
item.Add("b");
item.Add("fgs");
item.Add("adsd");

How can I find all items that start with (for example) "a"?

This "a" is not some hardcoded string, so I will need a function that do this for each string.

I try with FindAll, but I did not figured out how it works.

Br, Wolfy

like image 540
Wolfy Avatar asked Dec 16 '22 21:12

Wolfy


1 Answers

If by "start with" you mean the first char, then:

item.FindAll(i => i[0] == 'a');

if you mean a string (may be other than 1 char) then:

item.FindAll(i => i.StartsWith("a"));

If you want a different comparison, such as case-insensitive, locale-based, etc. then do the relevant IndexOf such as:

item.FindAll(i => i.IndexOf("a", StringComparison.CurrentCultureIgnoreCase) == 0);

All of the above can be easily adapted to be use a relevant char or string variable or parameter.

If you don't need the extra properties and methods provided by a list, then it will be more efficient to use Where than FindAll as FindAll creates a new list, and does so in all at once, while Where will enumerate the matching results as it is iterated through.

like image 140
Jon Hanna Avatar answered Dec 19 '22 12:12

Jon Hanna