1

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
3
  • 2
    So, by "custom" order you mean "alphabetical" order? :) Commented Dec 6, 2013 at 17:55
  • you don't need to order by character like so, just compare the strings. Commented Dec 6, 2013 at 17:55
  • This seems to me alphabetical order. But also you can write your own comparer class and using that in the sort method Commented Dec 6, 2013 at 17:58

3 Answers 3

4

In order to sort a list in an alphabetical order,you should use the built-in Sort function:

kmerList.Sort();
Sign up to request clarification or add additional context in comments.

2 Comments

and if it would be inverse order T->G->C->A?
kmerList.Sort().Reverse()
1

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();

Comments

1

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

Comments

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.