Below is the sample code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<String> myStringList = new List<string>();
Dictionary<string, int> UniqueList = new Dictionary<string, int>();
myStringList.Add("Red");
myStringList.Add("blue");
myStringList.Add("Red");
myStringList.Add("blue");
myStringList.Add("green");
myStringList.Add("blue");
myStringList.Add("green");
myStringList.Add("Ornage");
myStringList.Add("Yellow");
foreach (string s in myStringList)
{
if (!UniqueList.ContainsKey (s))
{
UniqueList.Add(s, 1);
}
else
{
int i = UniqueList[s];
UniqueList.Remove(s);
int count = i + 1;
UniqueList.Add(s, count);
}
}
//Display
// Store keys in a List
List<string> list = new List<string>(UniqueList.Keys);
// Loop through list
foreach (string k in list)
{
Console.WriteLine("{0}, {1}", k, UniqueList[k]);
}
}
}
}
and this is the o/p
No comments:
Post a Comment