ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Paramaters

This extension method will return all the parameters of an Uri in a Dictionary<string, string>. In case the uri doesn't contain any parameters a empty dictionary will be returned. Somehow I can't believe there is no standard method to do this though... Any additions and/or comments are quite welcome :)

Source

using System;
using System.Collections.Generic;
using System.Linq;

namespace Util {
  public static class UriExtentions {
    public static Dictionary<string, string> Parameters( 
      this Uri self ) {
      
      return String.IsNullOrEmpty( self.Query )
        ? new Dictionary<string, string>( )
        : self.Query.Substring( 1 ).Split( '&' ).ToDictionary(
            p => p.Split( '=' )[ 0 ],
            p => p.Split( '=' )[ 1 ]
        );
    }
  }
}

Example

Uri 
  without = new Uri( "http://www.abc.com" ),
  with    = new Uri( "http://www.abc.com?v=1" ),
  with2   = new Uri( "http://www.abc.com?v=1&v2=2" );

without.Parameters( ); // Empty dictionary
with.Parameters( );    // <string, string>{{"v", "1"}}
with2.Parameters( );   // <string, string>{{"v", "1"}, {"v2", "2"}}

Author: Andre Steenveld

Submitted on: 14 okt. 2010

Language: C#

Type: System.Uri

Views: 4964