1

I have a list of trees

   List<Tree> trees;
   ...
   filter_trees = trees.Distinct().ToList();

I want to select distinct trees, it works based on equality function of Tree class to distinguish distinct trees. Now I need to order these distinct trees based on their frequency (count) in the trees.

It may need a group by statement, however I prefer Distinct as it has no argument and works based on the specific Equals function I wrote.

Ahmad
  • 8,811
  • 11
  • 76
  • 141

1 Answers1

4

You can still do it all in one LINQ chain. GroupBy will respect your equality comparison, then you can select a complex item which contains both a tree and a count, then sort by the count, then pull out the tree.

var orderedTrees = trees
    .GroupBy(t => t)
    .Select(g => new
        {
            Tree = g.Key,
            Count = g.Count()
        })
    .OrderBy(x => x.Count)
    .Select(x => x.Tree)
    .ToList();
Joe Enos
  • 39,478
  • 11
  • 80
  • 136