0

How can I use lambda inside an if statement to compare a treenode's value to an object value inside a list ? Currently I am trying something like this but it won't work. Is there any better way to simplify my search?

if (tvItems.Nodes.Count > 0)
{
    // Get checked items
    listChecked= MenuItemDTOManager.GetMenuItems();
    //

    foreach (TreeNode parentNode in tvItems.Nodes)
    {
        if (listChecked.Find(s => s.menuId.ToString() == parentNode.Value.ToString()))
        {
            parentNode.Checked = true;
        }
    }
    // Traverse children
}
2
  • 3
    Yes, you can since you are already showing a lambda inside an if statement. But what is it that you are trying to do? And what doesn't work? Commented Oct 30, 2012 at 7:56
  • That was not working since if returns bool & Find does not. However I have found the answer thanks to @Cuong Le Commented Oct 30, 2012 at 9:19

3 Answers 3

4

Should be using Any instead of Find:

if (listChecked.Any(s => s.menuId.ToString() == parentNode.Value.ToString()))
{
    parentNode.Checked = true;
}
Sign up to request clarification or add additional context in comments.

Comments

2

if requires a bool value only.

listChecked.Find(s => s.menuId.ToString() == parentNode.Value.ToString())

Find won't return bool.

Try using Exists instead of Find.

Comments

1

Probably you are looking for the following.

foreach (TreeNode parentNode in tvItems.Nodes.OfType<TreeNode>().Any(n=> listChecked.Any(s => s.menuId.ToString() == n.Value.ToString()))
{
    parentNode.Checked = true;
}

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.