Friday, May 17, 2013

Convert Dictionary To String in C#.net


 
public staticclass ExtensionCLS

{

public static string ConvertDictinaryToString<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)

{


return string.Join(",", dictionary.Select(kv => kv.Key.ToString().Trim() + "*" + kv.Value.ToString().Trim()).ToArray());

}

 



}



//Create a dictionary Dictionary<string, string> MyList = new Dictionary<string, string>();

MyList.Add(
"A", "Apple");

MyList.Add(
"B", "Book");

MyList.Add(
"C", "Cat");

MyList.Add(
"D", "Dog");

MyList.Add(
"E", "Egg");


string returnString = "";

// Call the following dictionary to string
returnString =
ExtensionCLS.ConvertDictinaryToString(MyList);


Console.WriteLine(returnString);


Console.ReadLine();


Output: A*Apple,B*Book,C*Cat,D*Dog,E*Egg

No comments:

Post a Comment