2011-03-30 73 views
1

我正在试图制作一个Facebook应用程序,我可以管理我的朋友。现在我正在进行一些高级搜索。我使用FQL和LINQ to XML来适应我的搜索。可重复使用的Linq到XML方法来过滤我的查询结果

但我希望我的搜索方法可以重复使用。所以我可以合并多个过滤器。

这里是我的想法:

private var friends; 


public setFriends(XDocument doc) 
     { 
      friends = (from usr in doc.Descendants("user") 

        select new User 
        { 
         name = usr.Element("name").Value, 
         email = usr.Element("email").Value, 
         pic = usr.Element("pic_square").Value, 
         city = usr.Element("city").Value, 


        }); 

     return friends; 

    } 



public void filterFriendsByName() 
    { 
     friends = // some code to filter my previous results by name 
    } 

public void filterFriendsByCity() 
    { 
     friends = // some code to filter friends by city 
    } 

//more filters 

正如你所看到的,我仍然在这里缺少一些代码。我不知道我是否仍然可以从这里修改我的查询。我希望你能告诉我如何做到这一点。或者,请指出我朝着正确的方向努力做到这一点。

谢谢!

+1

您的setFriends有一个return语句,但没有定义返回类型。另外,如果你设置了一个成员变量(朋友),你不需要返回它。最后,你不能定义私人变种朋友。因为不能初始化匿名类型。所以,如果你有私人的IEnumberable 朋友,那很好。 – taylonr 2011-03-30 13:49:13

回答

4

你的代码很混乱,不会编译。但是当你清理它并纠正错误时,最后你会看到friends变量将得到IEnumerable<User>。之后,您可以继续过滤filterFriendsByName方法,就像这样。

public void filterFriendsByName(string name) 
{ 
    return friends.Where(x=> x.name == name); 
} 

friends将不会改变,但上述方法将返回过滤朋友的名字。同城

+0

是的,我只是简化了我的查询在这里更容易理解。 Thx的答复,我会立即尝试。我希望我可以将此标记为答案。因为它更复杂,因为我正在处理多个嵌套的select语句。我希望我也可以使用你的解决方案嵌套查询。 – ThdK 2011-03-30 14:06:14

+0

无论你有多少嵌套选择 - 它会工作。这就是所谓的链接。调用setFriends时应用第一个过滤器。 filterFriendsByName添加另一个过滤器链等。在评估IEnumerable开始时,它会逐一评估链。请参阅[Query Expressions](http://msdn.microsoft.com/zh-cn/library/bb397676.aspx) – archil 2011-03-30 14:15:04