c# - 将动态转换为Lambda表达式

时间:2011-05-13 13:05:36

标签: c# asp.net dynamic lambda

编码平台:ASP.NET C#4.0

我有以下代码段

public string PageID { get { return "20954654402"; } }
dynamic accounts = fb.Get("me/accounts");
if (accounts != null)
{
    bool isFound = false;
    foreach (dynamic account in accounts.data)
    {
        if (account.id == PageID)
        {
            isFound = true;
            break;
        }
    }
    if (!isFound)
    {
        //  user not admin
    }
    else
    {

    }
}

两个问题

  1. 为什么(account.id == PageID)错误(PageID是字符串属性) 更新:这是一个愚蠢的无关错误,因为我在PageMethods调用所有这些。
  2. 是否有更简单的C#4.0更改方式来更改foreach循环?
  3. 更新

    来自对Facebook API的调用的响应。样本将是

    {
        [{
            "name": "Codoons",
            "category": "Computers/technology",
            "id": "20954694402",
            "access_token": "179946368724329|-100002186424305|209546559074402|Hp6Ee-wFX9TEQ6AoEtng0D0my70"
        }, {
            "name": "Codtions Demo Application",
            "category": "Application",
            "id": "1799464329",
            "access_token": "179946368724329|-100002186424305|179946368724329|5KoXNOd7K9Ygdw7AMMEjE28_fAQ"
        }, {
            "name": "Naen's Demo Application",
            "category": "Application",
            "id": "192419846",
            "access_token": "179946368724329|61951d4bd5d346c6cefdd4c0.1-100002186424305|192328104139846|oS-ip8gd_1iEL9YR8khgrndIqQk"
        }]
    }
    

    稍微更新了代码。

    目的是获取与account.id匹配的PageID并获取与access_token相关联的account.id

    感谢您的时间。

5 个答案:

答案 0 :(得分:1)

您可以使用LINQ方法替代foreach:

if(accounts.Any(a => a.id == PageID))
{
    //  user not admin
}
else
{

}

至于为何“错误”:我们不能这么说,因为我们不知道id是什么类型。但如果id的类型为int,则可以解释错误。

答案 1 :(得分:0)

如果可以在另一个线程上修改(插入,删除)帐户集合,则foreach将在发生异常时抛出异常(简单的for循环不会)。

答案 2 :(得分:0)

当使用带有字符串的==,即PageID是一个字符串时,则account.id也应该是一个字符串,而不是一个int或float,也许这就是导致错误的原因

答案 3 :(得分:0)

accounts.data.Any(a => a.id.ToString() == PageID)

答案 4 :(得分:0)

您应该使用动态谓词。像这样:


var pagesWithId = (Predicate)((dynamic x) => x.id == PageId);
var pagesFound = accounts.FindAll(pagesWithId);

if(pagesFounds.Count() > 0)
 //do your thing

相关问题