0

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;
                }
            }
        }   
    }
}
0

1 Answer 1

1

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;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Worked fine. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.