Search code examples
linqsortingalphabetical-sort

LinQ OrderBy specific element in sublist


I have a Category class

public class Category
{
   public long Id { get; set; }
   public Translation[] Translations { get; set; }
}

and a Translation class

public  class Translation
{
   public string Locale { get; set; }
   public string Name { get; set; }
}

I then have a List of Categories List<Category> that is populated with category objects. I want to order my unorderedCategoryList alphabetically by the Name field in Translation based on specified Locale.

So for example I have 3 categories:

{1, ["EN","aaa"], ["RU","zzz"]}

{2, ["EN","ccc"], ["RU","eee"]}

{3, ["EN","bbb"], ["RU","aaa"]}

Ordering them with specified locale EN would result in a list ordered like this:

{1, ["EN","aaa"], ["RU","zzz"]}
{3, ["EN","bbb"], ["RU","aaa"]}
{2, ["EN","ccc"], ["RU","eee"]}

and by RU like this:

{3, ["EN","bbb"], ["RU","aaa"]}
{2, ["EN","ccc"], ["RU","eee"]}
{1, ["EN","aaa"], ["RU","zzz"]}

This line of code is as far as I got but it doesn't seem to work :

var sortedList = unorderedCategoryList.OrderBy(go => go.Translations.Where(t => t.Locale == "EN").Select(t => t.Name)).ToList();

Solution

  • You could create a Custom Comparer for Category Type as follows.

    public class CategoryComparer : IComparer<Category>
    {
        private string _locale;
        public CategoryComparer(string locale)
        {
            _locale = locale;
        }
        public int Compare(Category x, Category y)
        {
            var orderedX = x.Translations.Where(c=>c.Locale.Equals(_locale)).OrderBy(c=>c.Name);
            var orderedY = y.Translations.Where(c=>c.Locale.Equals(_locale)).OrderBy(c=>c.Name);
            return orderedX.First().Name.CompareTo(orderedY.First().Name);
        }
    }
    

    Now you could sort as

    var sortByKey = "EN";
    var orderedList = list.OrderBy(x=>x,new CategoryComparer(sortByKey));
    

    Demo Code