c# - Converting dynamic into Lambda expression
Coding Platform: ASP.NET C# 4.0
I have the following snippet
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
{
}
}
Two questions
Why doesUpdate: That was a stupid unrelated error as I as calling all of these at PageMethods.(account.id == PageID)
errors (PageID is a string property)- Is there a simpler and more C#4.0 like way to change the
foreach
loop?
Update:
Its the response from a call to Facebook API. A sample will be
{
[{
"name": "Codoons",
开发者_JAVA百科"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"
}]
}
Updated code also a little bit.
The intention is to get the account.id
that matches with PageID
and get the access_token
associated with that account.id
Thank you for your time.
You can use the LINQ methods for an alternative to the foreach:
if(accounts.Any(a => a.id == PageID))
{
// user not admin
}
else
{
}
As to why it "errors": We can't say that, because we don't know what type id
is of. But if id
is of type int
, this would explain an error.
If the accounts collection can be modified (inserts, deletes) on another thread foreach will throw an exception when that happens (simple for loop won't).
When using == with a string i.e. PageID is a string, then the account.id should also be a string, not an int or float, maybe thats whats causing the error
accounts.data.Any(a => a.id.ToString() == PageID)
You should use a dynamic predicate. Something like this:
var pagesWithId = (Predicate)((dynamic x) => x.id == PageId);
var pagesFound = accounts.FindAll(pagesWithId);
if(pagesFounds.Count() > 0)
//do your thing
精彩评论