Evildommer5
Evildommer5

Reputation: 139

Show most occured in rank order #

I have a list consisting of duplicates, I want to create an output showing them in rank. e.g tom at the top because he has 100 entries and lilly at the bottom because it has 0.

is this possible to display a list with a rank corosponding to the number of times they appear in the list?

also display the number of times they appear next to them?

Upvotes: 0

Views: 258

Answers (4)

dtb
dtb

Reputation: 217361

var query = File
    .ReadLines("input.txt")
    .GroupBy(x => x)
    .Select(g => new { Key = g.Key, Count = g.Count() })
    .OrderByDescending(i => i.Count)
    .Take(20);

foreach (var item in query)
{
    Console.WriteLine("{0,5} {1}", item.Count, item.Key);
}

Upvotes: 0

Zruty
Zruty

Reputation: 8677

Here's a simple LINQ query that does remotely that.

List<string> list = new List<string> { "a", "b", "a", "c", "a", "d", "c" };
var counts = from item in list
             group item by item
                 into grp
                 orderby grp.Count() descending
                 select new
                            {
                                Value = grp.Key,
                                Count = grp.Count()
                            };
foreach (var item in counts)
    Console.WriteLine("{0} ({1})", item.Value, item.Count);

Upvotes: 0

spender
spender

Reputation: 120508

The following will give an IEnumerable where each item contains a representative item from the group and the number of times it occurs.

myList
    .GroupBy( item => item.Name )
    .OrderByDescending( g => g.Count() )
    .Select( g => new {item=g.First(), numOcurrences=g.Count() )

Upvotes: 1

vc 74
vc 74

Reputation: 38179

var groups = list.GroupBy(item => item);
var orderedGroups = groups.OrderByDescending(group => group.Count());
foreach (var group in orderedGroups)
{
  Console.WriteLine(string.Format("{0} - {1}", group.Key, group.Count());
}

Upvotes: 0

Related Questions