Zo Has
Zo Has

Reputation: 13028

Lambda inside if statement?

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
}

Upvotes: 0

Views: 236

Answers (3)

cuongle
cuongle

Reputation: 75306

Should be using Any instead of Find:

if (listChecked.Any(s => s.menuId.ToString() == parentNode.Value.ToString()))
{
    parentNode.Checked = true;
}

Upvotes: 4

k0stya
k0stya

Reputation: 4315

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;
}

Upvotes: 1

Azodious
Azodious

Reputation: 13872

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.

Upvotes: 2

Related Questions