开发者

Searching for String pattern in Generic List collection

I have a Generic List of String of filenames. I would like to grab only that values that match a specific pattern. I looked for some documentation on finding patterns within a List and found this MSDN article.

http://msdn.microsoft.com/en-us/library/x0b5b5bc%28VS.85%29.aspx#Y1440

I have cut some of the basic example and listed it here.

List<string> dinosaurs = new List<string>();

dinosaurs.Add("Compsognathus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Oviraptor");
dinosaurs.Add("Velociraptor");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Dilophosaurus");
dinosaurs.Add("Gallimimu开发者_运维问答s");
dinosaurs.Add("Triceratops");

// Search predicate returns true if a string ends in "saurus".
private static bool EndsWithSaurus(String s)
{
    if ((s.Length > 5) && 
        (s.Substring(s.Length - 6).ToLower() == "saurus"))
    {
        return true;
    }else{
        return false;
    }
}

Bool result = dinosaurs.Find(EndsWithSaurus);

I think I understand what is being done with ONE BIG exception. The method EndsWithSaurus is expecting a String to be passed in to it, yet I don't see where it is being pased in


if you're on .NET 3.5+ (using LINQ extension methods in the System.Linq namespace), you could do this which will return your subset of matches:

var results = dinosaurs.Where(d => d.EndsWith("saurus")).ToList();

To answer your other questions in regards to the example shown, first of all Find() only returns true/false if it locates a match, but not the matches themselves. Where() on the other hand, returns the subset that matches. I like LINQ for these types of queries (Where(), etc) because they work with any IEnumerable container (List, HashSet, Array, etc).

As to your question on how the string gets passed, the Find() method (and Where(), etc) take a delegate Func<string, bool> - since your list is a string container - that tells whether it matches or not, the example you showed passes in the name of the method, which assigns it to the delegate. This works as long as the method satisfies the signature of Func<string, bool> which means it takes a string and returns a bool.

Make sense?


You can think of the Find method as a looping through each value in the List that calls the delegate that you passed.

Note, it does not return bool. It returns the generic type of the List.

Basically, you could write your own:

string Find(List<string> dinosaurs)
{
    for (string dinosaur in dinosaurs)
    {
        if (EndsWithSaurus(dinosaur))
        {
            return dinosaur;
        }
    }

    return null;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜