Effectiveness of masking a string The assignment is to mask (or rather unmask) certain indexes from a string. Both the input string and the demasker are strings. An example shows how it's supposed to work.


  Input: "abcdefgh"
  Mask: "2-4,6"
  Output: "bcdf"


The index is one-based and we need not to worry about malicious users' entries. The entries are always separated by a comma and the limits (if not atomary) by a dash.

My current solution is this.

string input = "abcdefghijklmnopqrstuvwxyz";
string mask = "3-5,8,9-12,13,14,18-26";

Dictionary&lt;int, int&gt; intervals = mask.Split(',').ToDictionary(
  element =&gt; Convert.ToInt32(element.Split('-').First()),
  element =&gt; Convert.ToInt32(element.Split('-').Last()));
string substring = "";
foreach (KeyValuePair&lt;int, int&gt; entry in intervals)
  substring += input.Substring(entry.Key - 1, entry.Value - entry.Key + 1);


I'm unhappy with the way it looks right now, because I'd like it to be demasking using other method than foreach. Given that the strings are relatively short, there's no option of deploying a third party library.

Can the above be made smoother? All creative critique is welcome.
Do not use Dictionary when order matters.

Your code assumes that iterating over Dictionary will yield elements in the order in which they were added, but that's not guaranteed at all (emphasis mine):


  For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair&lt;TKey, TValue&gt; structure representing a value and its key. The order in which the items are returned is undefined.


And even if this wasn't an issue, the intervals logically are not keys and values, so that's another reason not to use dictionary.

In simple cases like this, consider using anonymous type:

var intervals = mask.Split(',').Select(
  element =&gt; new 
  {
      from = Convert.ToInt32(element.Split('-').First()),
      to = Convert.ToInt32(element.Split('-').Last())
  });