Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for a slicker way to convert delimited string to StringDictionary

Tags:

c#

I have created the following to expose some data as a regex match string as well as a StringDictionary. It feels like I could do this using LINQ with fewer lines.

private const string STREETTYPES = @"ALY|Alley|AVE|Avenue|BLVD|Boulevard|CIR|Circle|CT|Court|CTR|Center|DR|Drive|EXPY|Expressway|FWY|Freeway|HALL|Hall|HWY|Highway|JCT|Junction|LN|Lane|LP|Loop|PIKE|Pike|PKWY|Parkway|PL|Place|RD|Road|ST|Street|TER|Terrace|TPKE|Turnpike|TRL|Trail|WAY|Way";

  private static StringDictionary streetTypes = null;
  public static StringDictionary StreetTypes
  {
    get
    {
      if (streetTypes != null) return streetTypes;
      streetTypes = new StringDictionary();
      var streetArray = STREETTYPES.Split(PIPE);
      for (int i = 0; i < streetArray.Length-1; i = i+2)
      {
        streetTypes.Add(streetArray[i], streetArray[i + 1]);
      }
      return streetTypes;
    }
  }
like image 715
MarkDav.is Avatar asked Oct 11 '11 22:10

MarkDav.is


2 Answers

How about just:

private static readonly StringDictionary streetTypes = new StringDictionary
{
    {"ALY","Alley"},{"AVE","Avenue"},{"ALY","Alley"},{"BLVD","Boulevard"},{"CIR","Circle"},
    {"CT","Court"},{"CTR","Center"},{"DR","Drive"},{"EXPY","Expressway"},{"FWY","Freeway"},
    {"HALL","Hall"},{"HWY","Highway"},{"JCT","Junction"},{"LN","Lane"},{"LP","Loop"},
    ...        
};
like image 171
Marc Gravell Avatar answered Sep 27 '22 18:09

Marc Gravell


You could use Linq if you need to recompute - but if the dictionary is static just use the initializer:

var input = STREETTYPES.Split('|');
var dict = input.Select( (x,i) => new { Item = x, Index = i })
                .Where(x => x.Index % 2 == 0)
                .ToDictionary( x=> input[x.Index], x => input[x.Index + 1]);
like image 41
BrokenGlass Avatar answered Sep 27 '22 17:09

BrokenGlass