简体   繁体   中英

Sort by alphabetically and quantity in same list

I need sort by alphabetically (asc) and quantity (desc) in same list.

My start sample:

    using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        public class Item
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
        static void Main(string[] args)
        {
            var items = new List<Item>
            {
                new Item {Name = "CItem", Age = 10},
                new Item {Name = "AItem", Age = 10},
                new Item {Name = "BItem", Age = 10},
                new Item {Name = "AItem", Age = 10},
                new Item {Name = "CItem", Age = 10},
                new Item {Name = "AItem", Age = 10},
                new Item {Name = "AItem", Age = 10},
                new Item {Name = "BItem", Age = 10},
                new Item {Name = "BItem", Age = 10},
                new Item {Name = "BItem", Age = 10},
                new Item {Name = "BItem", Age = 10}
            };

            items.Sort((x, y) => String.CompareOrdinal(x.Name, y.Name));
        }
    }
}

This sample ordered alphabetically only.

Expected Result

  1. Name = "BItem", Age = 10
  2. Name = "BItem", Age = 10
  3. Name = "BItem", Age = 10
  4. Name = "BItem", Age = 10
  5. Name = "BItem", Age = 10
  6. Name = "AItem", Age = 10
  7. Name = "AItem", Age = 10
  8. Name = "AItem", Age = 10
  9. Name = "AItem", Age = 10
  10. Name = "CItem", Age = 10
  11. Name = "CItem", Age = 10

Any suggestion?

What you can do here is group the items by the name, order the groups by their size, and then flatten out the collection of groups into just the items in those groups.

var query = items.GroupBy(item => item.Name)
    .OrderByDescending(group => group.Count())
    .SelectMany(group => group);

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