在获取不同值时,基于列中值的计数进行排序

时间:2016-06-28 13:08:18

标签: linq

var acts = new List<MyClass>(new[] {
        new MyClass { Date = DateTime.Parse("01/01/2011"), acty = "james" },
        new MyClass { Date = DateTime.Parse("01/01/2011"), acty = "james" },
        new MyClass { Date = DateTime.Parse("01/01/2011"), acty = "alex" },
        new MyClass { Date = DateTime.Parse("01/01/2011"), acty = "james" },
        new MyClass { Date = DateTime.Parse("02/01/2011"), acty = "matt" },
        new MyClass { Date = DateTime.Parse("02/01/2011"), acty  = "jamie" },
        new MyClass { Date = DateTime.Parse("02/01/2011"), acty = "alex" },
        new MyClass { Date = DateTime.Parse("02/01/2011"), acty = "james" },
        new MyClass { Date = DateTime.Parse("02/01/2011"), acty = "james" },
        new MyClass { Date = DateTime.Parse("02/01/2011"), acty = "lucy" },
        new MyClass { Date = DateTime.Parse("02/01/2011"), acty = "alex" },
        new MyClass { Date = DateTime.Parse("03/01/2011"), acty = "james" },
        new MyClass { Date = DateTime.Parse("03/01/2011"), acty = "bob" },
        new MyClass { Date = DateTime.Parse("03/01/2011"), acty = "bob" },
        new MyClass { Date = DateTime.Parse("03/01/2011"), acty = "james" },
        new MyClass { Date = DateTime.Parse("03/01/2011"), acty = "james" },
        new MyClass { Date = DateTime.Parse("04/01/2011"), acty = "alex" },
        new MyClass { Date = DateTime.Parse("04/01/2011"), acty = "alex" },
        new MyClass { Date = DateTime.Parse("04/01/2011"), acty = "alex" }
    });

要从列表中获取不同的值,我使用以下代码..

var dacts = acts.Select(o =&gt; o.acty).Distinct()。ToList();

我希望根据acty count降序来订购dacts。

我查看了Linq distinct - Count,这与我的要求不同。

上述问题得到一列的不同值和另一列的不同计数。

但是,在我的情况下,我想要按相同列的计数排序的列的不同值

所以,我希望我的回答是......

james,alex,bob,jamie,lucy,matt

1 个答案:

答案 0 :(得分:0)

var dacts = acts.Select(o => o.acty).Distinct().OrderByDescending().ToList();

尝试这个。

 var distinctNames = acts.GroupBy(m => m.acty).Select(grp => new { name = grp.Key, count = grp.Count() }).OrderByDescending(k => k.count).ToList();