Question

Well, I got an object called Mamamia and inside of it has some string properties. I created a list of this object and populated it with 150 items.

I'm trying to use List.FindAll but I reaaally don't know how to do it. I've tried this way:

produto = products.FindAll(delegate(Mamamia cv) {return cv.LocalPackage.Remove(1,21) == cmbPackage.SelectedValue};

I don't know why the delegate is there, I just tried to copy from some other code on the internet.

Thanks in advance!

Was it helpful?

Solution

The delegate is there to see whether the value that you're testing is what you're looking for. The call to Remove looks worryingly like it's mutating the value though - that's rarely a good thing when you're looking through the list. I guess if it's a string then it's not too bad, although it may not be what you're after...

What are the types involved, and what are you looking for? Oh, and are you using C# 3 and/or .NET 3.5? That would make it easier (even C# 3 against .NET 2.0 means you could use a lambda expression instead of an anonymous method).

What's happening when you run the code at the moment? If it's just not finding anything, it may just be because you're testing for reference equality (if SelectedValue returns object).

Try this:

produto = products.FindAll(delegate(Mamamia cv) {
    return cv.LocalPackage.Remove(1,21).Equals(cmbPackage.SelectedValue);
});

EDIT:

It sounds like you only want a single value, and if you're using .NET 3.5 it would be more idiomatic to use LINQ in the first place. I would use:

string selectedText = (string) cmbPackage.SelectedValue;
Mamamia item = products.FirstOrDefault
                  (cv => cv.LocalPackage.Remove(1,21) == selectedText);
if (item != null)
{
    // Found it; otherwise item will be null
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top