2

I want to convert this this piece of code to a LINQ query as LINQ is much quicker than a foreach. I dont know how to go about doing it, can do basically simple LINQ queries.

What i am trying to do is get a specific field in the dictionary.

Dictionary<string, object> fieldLayout = null;
foreach (Dictionary<string, object> dic in pageLayout)
{
    if (dic[ "FIELD" ].ToString() == "123")
    {
        fieldLayout = dic;
        break;
    }
}
4
  • 2
    Why do you think that Linq is quicker than foreach? Do you need to optimize this code? Commented Jul 30, 2012 at 11:45
  • 2
    LINQ is not faster or slower than for-each.. Commented Jul 30, 2012 at 11:45
  • 1
    Yes i need to optimize the code Commented Jul 30, 2012 at 11:49
  • Why do you keep object, not string? Calling ToString() is not the best choice! Commented Jul 30, 2012 at 11:50

3 Answers 3

3

Firstly, LINQ is not faster than a foreach loop.

Here is the implementation:

Dictionary<string, object> fieldLayout = pageLayout.Where(x => x["FIELD"].ToString() == "123").FirstOrDefault();

Or even better:

Dictionary<string, object> fieldLayout = pageLayout.FirstOrDefault(x => x["FIELD"].ToString() == "123");
Sign up to request clarification or add additional context in comments.

1 Comment

I'd recommend to leave only the 2nd.
3

fieldLayout = pageLayout.FirstOrDefault(dic => dic["FIELD"].ToString() == "213");

1 Comment

Should be dic["FIELD"].ToString() like in the original code because the dictionary has values of type object. Otherwise you'd do a by-reference comparison which is not useful.
2

LINQ is hardly faster than foreach, but that's outside the scope here.

var fieldLayout = pageLayout.FirstOrDefault(pl => pl["FIELD"].ToString() == "123");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.