将动态转换为 Lambda 表达式
本文关键字:Lambda 表达式 转换 动态 | 更新日期: 2023-09-27 17:56:26
编码平台: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
{
}
}
两个问题
为什么更新:这是一个愚蠢的不相关的错误,因为我在PageMethods上调用所有这些错误。(account.id == PageID)
错误(PageID 是一个字符串属性)- 有没有更简单、更像 C#4.0 的方法来更改
foreach
循环?
更新:
它是对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"
}]
}
更新的代码也一点点。
目的是获取与PageID
匹配的account.id
,并获取与该account.id
关联的access_token
谢谢你的时间。
可以使用 LINQ 方法替代 foreach:
if(accounts.Any(a => a.id == PageID))
{
// user not admin
}
else
{
}
至于为什么会"出错":我们不能这么说,因为我们不知道id
是什么类型。但是如果id
是int
型,这将解释一个错误。
如果可以在另一个线程上修改帐户集合(插入、删除),则发生这种情况时将引发异常(简单 for 循环不会)。
当将 == 与字符串一起使用时,即 PageID 是一个字符串,那么 account.id 也应该是一个字符串,而不是 int 或浮点数,也许这就是导致错误的原因
accounts.data.Any(a => a.id.ToString() == PageID)
您应该使用动态谓词。像这样:
var pagesWithId = (Predicate)((dynamic x) => x.id == PageId);
var pagesFound = accounts.FindAll(pagesWithId);
if(pagesFounds.Count() > 0)
//do your thing