最好的c#语法/成语,从Facebook阅读数组的朋友 [英] best c# syntax/idiom, reading array of friends from Facebook

查看:139
本文介绍了最好的c#语法/成语,从Facebook阅读数组的朋友的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c#中,我只是从FB api抓取/ me / friends,

  private void FacebookFriends )
{
FB.API(/ me / friends,HttpMethod.GET,FBAPIFriendsCallback);
}

private void FBAPIFriendsCallback(FBResult response)
{
//(错误处理这里 - 没问题)

//丑陋代码...
var dict = Json.Deserialize(response.Text)
作为字典< string,object> ;;
var friendList = new List< object>();
friendList =(List< object>)(dict [data]);
int _friendCount = friendList.Count;

// ugly code ...
//(示例显示获取一个项目,将循环遍历)
string id = getDataValueForKey(
(Dictionary< string ,object>)(friendList [0]),id);
string name = getDataValueForKey(
(Dictionary< string,object>)(friendList [0]),name);
}

注意非常非常丑的代码 - 更优雅的写法方式是什么这个?干杯






事实上,根据下面的swazza的评论,这里是完整的代码段:


$使用UnityEngine b $ b

  
使用System.Collections;
使用System.Collections.Generic;
使用Parse;
使用系统;
使用Facebook;
使用System.Threading.Tasks;
使用System.IO;
使用System.Linq;
使用Facebook.MiniJSON;


public class ParseLinkOps:MonoBehaviour
{

...

public void GetFriendsFromFBThenMatch()
{
FB.API(/ me / friends,HttpMethod.GET,_cbFriends);
// FB调用
// https://developers.facebook.com/docs/unity/reference/current
}

private void _cbFriends(FBResult响应)
{
//目标:给出云的json结果,
//创建一个列表< string>只包含FacebookIDid数字

if(!String.IsNullOrEmpty(response.Error))
{// ..错误处理.. return;

var dict = Json.Deserialize(response.Text)
作为字典< string,object> ;;

var friendList = new List< object>();
friendList =(List< object>)(dict [data]);

int _friendCount = friendList.Count;
Debug.Log(在FB上找到朋友,_friendCount ...+ _friendCount);

//所以,将FB对象的复杂数组
//转换为一个id字符串数组
//使用非常丑的代码,但假设某人在SO以后知道更好:-)

列表< string> friendIDsFromFB = new List< string>();

for(int k = 0; k< _friendCount; ++ k)
{
string friendFBID =
getDataValueForKey((Dictionary< string,object> friendList [k]),id);

string friendName =
getDataValueForKey((Dictionary< string,object>)(friendList [k]),name);

Debug.Log(k +/+ _friendCount ++ friendFBID ++ friendName);

friendIDsFromFB.Add(friendFBID);
}

//我们完成了,列表在friendIDsFromFB
StartCoroutine(_match(friendIDsFromFB));
}

...
}


解决方案

如何使用linq扩展?

  var dict = new Dictionary< string,object> (); 
var friend = dict
.Where(s => s.Key.Equals(data))
.Select(s => new {Id = s.Key,Name = s.Value})
.First();

var friendId = friend.Id;
var friendName = friend.Name;

这是一个linq扩展,用于遍历可枚举并对每个元素执行一个操作 -

  public static void执行< TSource>(此IEnumerable< TSource>源,Action< TSource> actionToExecute)
{
if(source.Count()> 0)
{
foreach(源中的var item)
{
actionToExecute(item);
}
}
}

编辑:所以我明白你在Unity游戏引擎中使用这个。自从我在Unity上工作以来,已经过去了。很高兴知道他们现在支持林克。所以这里是我写的代码,得到friendIds。有一些特定于ASP.Net的代码,但linq部分应该在任何地方工作 -

  //使用ASP.Net的Javascript序列化器去尝试从
收到的json响应//调用graph.facebook.com/me/friends
var jsSerializer = new JavaScriptSerializer();
var jsonString ={\data\:[{\name\:\name1\,\id\:\id1\ },{\name\:\name2\,\id\:\id2\}]}

//将json反序列化为类型 - 字典< string,object>
var dict = jsSerializer.Deserialize(jsonString,typeof(Dictionary< string,object>))as Dictionary< string,object> ;;

/ *这里的代码特定于ASP.Net - 在这一点上,无论是ASP.Net还是Unity,我们都有一个包含一个键数据的字典,它再次包含一个名称的字典值对* /

//下面的代码是Linq,也应该在Unity上工作。
var friendIds =(dict [data] as ArrayList)//将字典的data键转换为其底层类型(在这种情况下为ArrayList)
.Cast< Dictionary< string,object>>()// ArrayList不是通用的。将其转换为通用枚举,其中每个元素的类型为Dictionary< string,object>
.Select(s =>
{
// cast枚举中的每个元素都是字典类型
//每个字典都有两个键 - id和名称,与调用graph.facebook.com/me/friends时收到的json响应的id和name属性
//相对应。
//检查 - https://developers.facebook.com /tools/explorer/145634995501895/?method=GET&path=me%2Ffriends&version=v2.0
//因为我们只需要Ids,所以获取与id键对应的值
对象id = null;
if(s.TryGetValue(id,out id))
{
return id.ToString();
}

返回string.Empty;
});

我放入了详细的注释,使该代码有点自我解释。如果您删除注释,则会使代码更简洁。但是,这比普通的循环性能要差。


In c#, I'm simply grabbing "/me/friends" from the FB api,

private void FacebookFriends()
    {
    FB.API("/me/friends", HttpMethod.GET, FBAPIFriendsCallback);
    }

private void FBAPIFriendsCallback(FBResult response)
    {
    // (error handling here - no problem)

    // ugly code...
    var dict = Json.Deserialize(response.Text)
        as Dictionary<string,object>;
    var friendList = new List<object>();
    friendList = (List<object>)(dict["data"]);
    int _friendCount = friendList.Count;

    // ugly code...
    // (example shows getting one item, would loop through all)
    string id = getDataValueForKey(
          (Dictionary<string,object>)(friendList[0]), "id" );
    string name = getDataValueForKey(
          (Dictionary<string,object>)(friendList[0]), "name" );
    }

Notice the very, very ugly code -- what's the more elegant way to write this? Cheers


In fact, per swazza's comment below, here's the full code passage:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Parse;
using System;
using Facebook;
using System.Threading.Tasks;
using System.IO;
using System.Linq;
using Facebook.MiniJSON;


public class ParseLinkOps : MonoBehaviour
  {

  ...

  public void GetFriendsFromFBThenMatch()
    {
    FB.API("/me/friends", HttpMethod.GET, _cbFriends);
    // FB calls at
    // https://developers.facebook.com/docs/unity/reference/current
    }

  private void _cbFriends(FBResult response)
    {
    // goal: given the json result from the cloud,
    // create a List<string> containing only the FacebookID "id" numbers

    if ( ! String.IsNullOrEmpty(response.Error) )
      { // .. error handling .. return; }

    var dict = Json.Deserialize(response.Text)
            as Dictionary<string,object>;

    var friendList = new List<object>();
    friendList = (List<object>)(dict["data"]);

    int _friendCount = friendList.Count;
    Debug.Log("Found friends on FB, _friendCount ... " +_friendCount);

    // so, convert that complex array of FB objects,
    // to simply an array of "id" strings
    // use very ugly code but assume someone on SO knows better later :-)

    List<string> friendIDsFromFB = new List<string>();

    for ( int k=0; k<_friendCount; ++k)
      {
      string friendFBID =
        getDataValueForKey( (Dictionary<string,object>)(friendList[k]), "id");

      string friendName =
        getDataValueForKey( (Dictionary<string,object>)(friendList[k]), "name");

      Debug.Log( k +"/" +_friendCount +" " +friendFBID +" " +friendName);

      friendIDsFromFB.Add( friendFBID );
      }

    // we're done, the list is in friendIDsFromFB
    StartCoroutine( _match( friendIDsFromFB ) );
    }

  ...
  }

解决方案

How about using linq extensions?

var dict = new Dictionary<string, object>();
var friend = dict
            .Where(s => s.Key.Equals("data"))
            .Select(s => new { Id = s.Key, Name = s.Value })
            .First();

var friendId = friend.Id;
var friendName = friend.Name;

Here is a linq extension to iterate over an enumerable and perform an action on each element -

public static void Execute<TSource>(this IEnumerable<TSource> source, Action<TSource> actionToExecute)
{
    if (source.Count() > 0)
    {
        foreach (var item in source)
        {
            actionToExecute(item);
        }
    }
}

EDIT: So I understand that you are using this in Unity game engine. Its been ages since I worked on Unity. Glad to know they have support for Linq now. So here is the code that I wrote that get the friendIds. There is some code that is specific to ASP.Net but the linq part should work anywhere -

// Use ASP.Net's Javascript serializer to desrialize the json response received from 
// call to graph.facebook.com/me/friends
var jsSerializer = new JavaScriptSerializer();
var jsonString = "{ \"data\": [ { \"name\": \"name1\", \"id\": \"id1\" }, { \"name\": \"name2\", \"id\": \"id2\" } ] }";

// Deserialize the json to type - Dictionary<string, object>
var dict = jsSerializer.Deserialize(jsonString, typeof(Dictionary<string, object>)) as Dictionary<string, object>;

/*Code upto here is specific to ASP.Net - At this point, be it ASP.Net or Unity, we have a dictionary that contains a key "data" which again contains a dictionaries of name value pairs*/

// The code from below is Linq and should work on Unity as well.
var friendIds = (dict["data"] as ArrayList)                     // Convert the "data" key of the dictionary into its underlying type (which is an ArrayList in this case)
                .Cast<Dictionary<string, object>>()             // ArrayList is not generic. Cast it to a generic enumerable where each element is of type Dictionary<string, object> 
               .Select(s =>
                            {
                                // Each element in the cast enumerable is of type dictionary.
                                // Each dictionary has two keys - "id" and "name" that correspond to the id and name properties 
                                // of the json response received when calling graph.facebook.com/me/friends.
                                // check - https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=me%2Ffriends&version=v2.0
                                // Because we only want Ids, fetch the value corresponding to the "id" key
                                object id = null;
                                if (s.TryGetValue("id", out id))
                                {
                                    return id.ToString();
                                }

                                return string.Empty;
                            });

I put in verbose comments to make that code a bit self explanatory. If you remove the comments, it makes for concise code. However, this is less performant than a plain for loop.

这篇关于最好的c#语法/成语,从Facebook阅读数组的朋友的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆