Facebook Graph API – Getting Friends and Gender in C#

I recently blogged about the Facebook Graph API and if you have the Facebook C# SDK you can start making applications.

After I had my Facebook app set up, I started making a C# Console application to just get my friends and see what I could do. Here is a snippet to get my friends and their gender.

       string token = <YOUR TOKEN HERE>;
            Facebook.FacebookAPI api = new Facebook.FacebookAPI(token);
            JSONObject f = api.Get("/me/friends");
            KeyValuePair<String, JSONObject> friends = f.Dictionary.ElementAt(0);
            for (int i = 0; i < friends.Value.Array.Count(); i++)
                Console.WriteLine("Friend #" + i.ToString());
                JSONObject friend = api.Get("/" + friends.Value.Array[i].Dictionary["id"].String);
                catch(System.Collections.Generic.KeyNotFoundException knfe)
                    Console.WriteLine("No Gender Specified");

There is a probably a better way to do this, but getting the JSONObject back and then getting the values you get back from that, I just kind of brute forced it. Also, handling friends that don’t have information set, the quick and dirty way was to just catch the exception. I know there has to be a better way but for now it works.