Skip to content

LINQ HELP

David Smith

Asked Jul 25, 2012, 1:27 PM EDT2 answers
Share
LinkedInX
I need some LINQ help.

I have an object (TreeNodeCollection) that contains an object (Nodes), also of type TreeNodeCollection.  I wish to know how many of those sub-nodes have a count of not equal to zero.  Below is the code I am using.  There should be a better way to get the count other than selecting all the items and using the Count function.  Can you help?


         var a = from TreeNode x in nodes where x.Nodes.Count != 0 select x;
         int numTasks = a.Count();

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    TopTask1
        Task1
            test1
            test2
        Task2
            Task2.1
                test1
            test1
    TopTask2
        test1


    Given TopTask1.Nodes, the count should be 2 (Task1 and Task2).

    Given Task2.Nodes, the count should be 1 (Task2.1, since its Nodes.Count is 1).  Note that Task2.Nodes.Count == 2, but I want to exclude Task2.1 | test1 since its Nodes.Count is 0.
    0
  • 0
    I want to turn this logic below into LINQ using one line of code below

    public int countTasks(TreeNode x)
    {
    int taskCount = 0;
    foreach(var node in x.Nodes)
    {
    if (node.Count > 0)

    {
    taskCount++;
    }

    }
    return taskCount;
    } 
    0