简体   繁体   中英

How to sort list<string> in custom order

Having a string like "CAATCCAAC" I am generating all kmers from it (k is variable but has to be less than string) doing:

        string dna = "CAATCCAAC";
        dna = dna.Replace("\n", "");
        int k = 5;
        List<string> kmerList = new List<string>();
        var r = new Regex(@"(.{" + k + @"})");
        while (dna.Length >= k)
        {
            Match m = r.Match(dna);
            //Console.WriteLine(m.ToString());
            kmerList.Add(m.ToString()); 
            dna = dna.Substring(1);
        }
        var sortedList = kmerList.OrderBy(i =>'A').
                        ThenBy(i => 'C').
                        ThenBy(i => 'G').
                        ThenBy(i => 'T').ToList();
        foreach (string result in sortedList) 
        {
            Console.WriteLine(result);
        }

I want to sort result

 AATCC
 ATCCA
 CAATC
 CCAAC
 TCCAA

However I am getting

CAATC
AATCC
ATCCA
TCCAA
CCAAC

How can I sort elements so they are ordered first by 'A' then by 'C' then by 'G' and finally 'T' ?

I tried

var sortedList = kmerList.OrderBy(i =>'A').
                            ThenBy(i => 'C').
                            ThenBy(i => 'G').
                            ThenBy(i => 'T').ToList();

but that wouldn't work

I want the result like to be aplied for all string like

AAAA
AACG
ACCC
ACCG
ACCT
...

TTTT

为了按字母顺序对列表进行排序,您应该使用内置的Sort函数:

kmerList.Sort();

There's a build-in sort function. Try kmerList.Sort()

If you want to order in alphabetical order you can use:

List<string> sorted = kmerList.OrderBy(x => x).ToList();

To get the reverse:

List<string> sorted = kmerList.OrderByDescending(x => x).ToList();

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