开发者

FindAll search question

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


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.


Or with LINQ

from i in items where i.StartsWith("a") select i;


for NET2.0 you may use this method: 'pattern' is an argument to look for (f.e. "a")

    private List<string> FindAll(List<string> list, string pattern)
    {       // returns found results
            return list.FindAll(delegate(string item)
                            {
                                return item.StartsWith(pattern);

                            });
    }


I thought you have another list that contains the startswith criteria strings. Lets call your items "words" and the other list "keywords". So the below query will return what you want.

List<string> words = new List<string>();
words.Add("a");
words.Add("as");
words.Add("b");
words.Add("fgs");
words.Add("adsd");

List<string> keywords = new List<string>();
keywords.Add("a");
keywords.Add("b");

var result = words.FindAll(o =>
    keywords.Any(a => o.StartsWith(a))
);

This result has the words that starts with any of the keyword from keywords.


List<string> item = new List<string>();
            item.Add("a");
            item.Add("as");
            item.Add("b");
            item.Add("fgs");
            item.Add("adsd");

            var res1 = item.FindAll(i => i.StartsWith("a"));
            var res2 = item.Where(i => i.StartsWith("a"));


Try this

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

This will return a List containting only the filtered strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜