简体   繁体   English

列表顺序不同的项目(按其在列表中的计数)

[英]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. 我想选择不同的树,它基于Tree类的相等函数来区分不同的树。 Now I need to order these distinct trees based on their frequency (count) in the trees . 现在,我需要订购基于其频率(计数),这些不同的树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. 它可能需要一个group by语句,但是我更喜欢Distinct因为它没有参数,并且基于我编写的特定Equals函数工作。

You can still do it all in one LINQ chain. 您仍然可以在一个LINQ链中完成所有操作。 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. GroupBy将尊重您的相等性比较,然后您可以选择一个包含树和计数的复杂项,然后按计数排序,然后拉出树。

var orderedTrees = trees
    .GroupBy(t => t)
    .Select(g => new
        {
            Tree = g.Key,
            Count = g.Count()
        })
    .OrderBy(x => x.Count)
    .Select(x => x.Tree)
    .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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