Monday, March 24, 2014

C# Cool Code Tips

1.Specialized Collection- NameValueCollection
Real time example
Parse a string such as "p1=6&p2=7&p3=8" into a NameValueCollection

NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);

qscoll["p1"] , qscoll["p2"] and qscoll["p3"]                

Speciality- This NameValueCollection can hold duplicates Key with different Values.

   // Creates and initializes a new NameValueCollection.
      NameValueCollection myCol = new NameValueCollection();
      myCol.Add( "red", "rojo" );
      myCol.Add( "green", "verde" );
      myCol.Add( "blue", "azul" );
      myCol.Add( "red", "rouge" );

 public static void PrintKeysAndValues2( NameValueCollection myCol )  {
      Console.WriteLine( " [INDEX] KEY VALUE" );
      for ( int i = 0; i < myCol.Count; i++ )
         Console.WriteLine( " [{0}] {1,-10} {2}", i, myCol.GetKey(i), myCol.Get(i) );

Displays the elements using
GetKey and Get:   
[0]     red rojo,rouge   
[1]     green verde   
[2]     blue azul

2. Array.ConvertAll
Real Time Example
You have string  with comma separated with integer value and you want to have int[] conversion from string [] array.

look at this now!

string commaSep= "1,2,3"
int[] transform= Array.ConvertAll(commaSep.split(','),s=>int.parse(s))
Post a Comment