简体   繁体   中英

Distinct items of list order by their count in the list

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM