tags:

views:

260

answers:

1

Hello!

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!

+1  A: 

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
}
Jon Skeet
I'm using .NET 3.5 and when I run the code, I'm getting the error:Cannot implicitly convert type 'System.Collections.Generic.List<FindMSIProducts.Mamamia>' to 'FindMSIProducts.MamamiaI'm looking for a propertie inside a list of Mamamia objects
Felipe Barreiros
@Felipe: Is your `produto` variable of type `List<Mamamia>` or just `Mamamia` itself? If you just want to return a single item then use the `Find` method rather than `FindAll`. If you're expecting to return multiple items then change the type of `produto` to `List<Mamamia>`.
LukeH
produto is a Mamamia object and products is a List<Mamamia> this list can have duplicated items and I want to return all of them
Felipe Barreiros
How do you expect to return all of them if produto isn't a collection?
Jon Skeet
I think that I need to review C# basics...hahaha, thanks!
Felipe Barreiros