In my continued venture to teach myself C# I came across an exercise using Dictionary. I created a class that has a method. In that method it creates a dictionary with keys/values. A string is passed into that method. If any matching character in that string correlates with a key we increment the value of that key, else we throw an ArgumentException. This is my code an my first real attempt and working with a dictionary in C#.
I am interested to see if there is a better, concise, an/or faster way to do the same task. Following is my code and following that is the test. Test can not be altered. I tried turning foreach into linq without luck so that would be interesting to see that as well if you know how or recommend it.
For more information My Github link to this exercise.
using System;
using System.Collections.Generic;
public static class NucleotideCount
{
public static IDictionary<char, int> Count(string sequence)
{
Dictionary<char, int> Dna = new Dictionary<char, int>()
{
{'A', 0},
{'C', 0},
{'G', 0},
{'T', 0}
};
foreach (char c in sequence)
{
switch (c)
{
case 'A': Dna[c]++; break;
case 'C': Dna[c]++; break;
case 'G': Dna[c]++; break;
case 'T': Dna[c]++; break;
default : throw new ArgumentException("Strand has invalid nucleotides.");
}
}
return Dna;
}
}
// This file was auto-generated based on version 1.3.0 of the canonical data.
using System;
using System.Collections.Generic;
using Xunit;
public class NucleotideCountTests
{
[Fact]
public void Empty_strand()
{
var expected = new Dictionary<char, int>
{
['A'] = 0,
['C'] = 0,
['G'] = 0,
['T'] = 0
};
Assert.Equal(expected, NucleotideCount.Count(""));
}
[Fact]
public void Can_count_one_nucleotide_in_single_character_input()
{
var expected = new Dictionary<char, int>
{
['A'] = 0,
['C'] = 0,
['G'] = 1,
['T'] = 0
};
Assert.Equal(expected, NucleotideCount.Count("G"));
}
[Fact]
public void Strand_with_repeated_nucleotide()
{
var expected = new Dictionary<char, int>
{
['A'] = 0,
['C'] = 0,
['G'] = 7,
['T'] = 0
};
Assert.Equal(expected, NucleotideCount.Count("GGGGGGG"));
}
[Fact]
public void Strand_with_multiple_nucleotides()
{
var expected = new Dictionary<char, int>
{
['A'] = 20,
['C'] = 12,
['G'] = 17,
['T'] = 21
};
Assert.Equal(expected, NucleotideCount.Count("AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC"));
}
[Fact]
public void Strand_with_invalid_nucleotides()
{
Assert.Throws<ArgumentException>(() => NucleotideCount.Count("AGXXACT"));
}
}