codeandcloud
codeandcloud

Reputation: 55200

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

  1. Why does (account.id == PageID) errors (PageID is a string property) Update: That was a stupid unrelated error as I as calling all of these at PageMethods.
  2. 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",
        "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.

Upvotes: 2

Views: 444

Answers (5)

tucaz
tucaz

Reputation: 6684

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

Upvotes: 0

George Polevoy
George Polevoy

Reputation: 7671

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

Upvotes: 0

Drenai
Drenai

Reputation: 12347

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

Upvotes: 0

Ricibob
Ricibob

Reputation: 7705

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).

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

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.

Upvotes: 1

Related Questions