1

我有以下代码,基本上可以满足我的要求:

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);

如您所见,lambda 相当大。我宁愿在第一个 .Where 调用中有一个回调方法。但我不知道如何将 firstName 和 lastName 参数提供给该回调方法。

这甚至可能吗?

4

1 回答 1

1

您不能只将方法传递给 first Where,因为您还需要传递名字和姓氏,但您可以传递一个更简单的 lambda ......这是一个可能的重构:

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;
}
于 2013-06-02T19:33:40.303 回答