Juan Jesus
Juan Jesus

Reputation: 63

Sorting list in c# with linq

Im trying to order the names(ListaSTR) according to the order of the integers in ListaINT. Checked other post with this solution but is now working for me. Im newbie. What am I missing?

using System.Collections.Generic;
using System;
using System.IO;
using System.Text;
using System.Linq;


namespace Simple
{
    public static class Program
    {
        static void Main()
        {
            List<string> ListaSTR = new List<string>{"Alberto","Bruno","Carlos","Mario","Pepe","Rodrigo"};
            List<int> ListaINT = new List<int>{4,6,1,8,2,5};

            List<string> O_ListaSTR = OrderBySequence(ListaSTR, ListaINT, Func<string,string>);

            Console.WriteLine(O_ListaSTR);

            Console.ReadLine();
        }

        public static List<string> OrderBySequence<string, int>(this List<string> source, List<int> order, Func<string,int> idSelector)
        {
            var lookup = source.ToLookup(idSelector, t => t);
            foreach (var id in order)
            {
                foreach (var t in lookup[id])
                {
                   yield return t;
                }
            }
        }   
    }
}

Upvotes: 0

Views: 41

Answers (1)

Hadi Samadzad
Hadi Samadzad

Reputation: 1540

Try this:

    static void Main(string[] args)
    {
        List<string> ListaSTR = new List<string> { "Alberto", "Bruno", "Carlos", "Mario", "Pepe", "Rodrigo" };
        List<int> ListaINT = new List<int> { 4, 6, 1, 3, 2, 5 };

        var O_ListaSTR = ListaSTR.OrderBySequence(ListaINT);

        Console.WriteLine(O_ListaSTR);

        Console.ReadLine();
    }

And your extension method can be in a simple form like this:

public static IEnumerable<string> OrderBySequence(this List<string> source, List<int> order)
    {
        var result = new List<string>();
        foreach (var i in order)
        {
            result.Add(source[i - 1]);
        };

        return result;
    }

Upvotes: 1

Related Questions