2
\$\begingroup\$

Parent has list of Children. I only have access to the list of children. I need to get list of unique parents from the List of Children. Is there a better/faster/more efficient way of doing it than this?

var temp = new HashSet<Parent>(
                        (from child in program.Children
                        select child.Parent).ToList());
\$\endgroup\$
3
  • 8
    \$\begingroup\$ program.Children.Select(c => c.Parent).Distinct();. It wont be any faster though. \$\endgroup\$
    – RobH
    Jul 24, 2015 at 13:49
  • \$\begingroup\$ It's easier to read however. \$\endgroup\$ Jul 24, 2015 at 13:53
  • 1
    \$\begingroup\$ @RobH you should add your comment as an answer. \$\endgroup\$
    – Dan Lyons
    Jul 24, 2015 at 18:06

1 Answer 1

5
\$\begingroup\$

Your use of var is good, but names like temp is meaningless. It's a temp what exactly? A more descriptive name is in order here.

The call to ToList appears to be redundant. Hashset's constructor takes an IEnumerable<T> and Linq queries that return collections already return one.

I would also break the query away from the ctor for readability purposes.

var parents = from child in program.Children
                 select child.Parent;

var distinctParents = new HashSet<Parent>(allParents);

However, it's all kind of moot if you use the method syntax snippet that @RobH posted.

var parents = program.Children.Select(c => c.Parent).Distinct(); 
\$\endgroup\$
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.