1

I have the following code which basically does what I want:

string firstName = "Chuck";
string lastName = "Norris";

 filtered = dvds.Where(
            dvd => (dvd.Element("Actors") != null) && (dvd.Element("Actors").Elements("Actor").Where(
                actor => actor.Attribute("FirstName") != null && actor.Attribute("FirstName").Value == firstName 
                    && actor.Attribute("LastName") != null && actor.Attribute("LastName").Value == lastName)).Count() > 0);

As you can see, the lambda is quite big. I'd rather have a callback method in the first .Where call. But I don't see how I could give the firstName and lastName parameters into that callback method.

Is that even possible?

1 Answer 1

1

You can't just pass a method to the first Where, since you also need to pass the first and last names, but you can pass a simpler lambda... Here's a possible refactoring:

filtered = dvds.Where(dvd => HasActor(dvd, firstName, lastName));
...

bool HasActor(XElement dvd, string firstName, string lastName)
{
    var actors = dvd.Element("Actors");
    if (actors != null)
    [
        var actor = actor.FirstOrDefault(a => IsActor(a, firstName, lastName));
        return actor != null;
    }
    return false;
}

bool IsActor(XElement actor, string firstName, string lastName)
{
    string firstNameAttr = actor.Attribute("FirstName");
    string lastNameAttr = actor.Attribute("LastName");
    return firstNameAttr != null
        && firstNameAttr.Value == firstName
        && lastNameAttr != null
        && lastNameAttr.Value == lastName;
}
Sign up to request clarification or add additional context in comments.

1 Comment

slaps head Sometimes you don't see the forest for the trees. Of course(!) I can just call another method and pass on the additional parameters. Now I feel stupid. :-/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.