简体   繁体   中英

how to sort a string array based on elements of another List

I've a string array - lets imagine something like;

string[] Array = {a,b,c,d,e,a,b,c,d,e,a,b,c,d,e}

and I've a List - something like;

List<string> l = {a,b,c,d,e}

I need to sort Array like:

string[] sortedArray = {a,a,a,b,b,b,c,c,c,d,d,d,e,e,e}

My working is:

public static List<string> SortByList(List<string> values, List<string> order)
        {
            return values.OrderBy(x => order.IndexOf(x)).ToList();
        }
private void buttonGo_Click(object sender, EventArgs e)
        {
            List<string> alpha = new List<string>();
            List<string> m = new List<string>();
            string[] gamma = null;

            using (StreamWriter sw = File.CreateText(pathSave))
            {    
                foreach (string st in parts)
                {
                        alpha.Add(st);
                }
            }
            using (StreamReader sr = new StreamReader(pathSave, true))
        {
            gamma = File.ReadAllLines(pathSave);
            foreach (string i in gamma)
            {
                l.Add(i);
            }
            m = SortByList(l, alpha);
        }

        using (StreamWriter sw = File.AppendText(pathSave))
        {
            sw.Write("---------------------------------------------------------------------");
            foreach (string st in m)
            {
                sw.Write(st);
                sw.Write("\r\n");
            }
        }
        }

In short, alpha is a list of string elements and lines is a string Array. I want to sort lines with respect of elements in alpha . Can someone please guide. Thanks

I think you want to do something like this:

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

class Program
{
    static void Main()
    {
        var values = new List<string>{"a","b","c","d","e","a","b","c","d","e","a","b","c","d","e"};
        var order = new List<string>{"a","b","c","d","e"};

        var sortedList = SortByList(values, order);

        foreach(var i in sortedList)
        {
            Console.WriteLine(i);
        }
    }
    public static List<string> SortByList(List<string> values, List<string> order){
        return values.OrderBy(x => order.IndexOf(x)).ToList();
    }
}

Output: aaabbbcccdddeee

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