Remove duplicates from List of Dictionaries using Linq C#

Remove duplicates from List of Dictionaries using Linq C#

Dictionary:

Dictionary in C# is a collection of Keys and Values, where key is like word and value is like definition. System.Collections.Generic namespace provides numerous collections which can be extended in your code base to achieve certain tasks.

Following figure gives an overview of the generic interfaces and the generic classes of dictionaries. Blue figures represent interfaces and the red figures represent classes. .NET models dictionaries as IEnumerables and ICollections at the highest levels of abstractions. By following the figure we can directly read that a dictionary is a ICollection of KeyValuePairs.

Code example:

using System.Collections.Generic;
private void RemoveDuplicateFromListOfDict()
{
	//Declare dictionary
	List<Dictionary<string, string>> odictionary = new List<Dictionary<string, string>>();
	
	//Populating values
	odictionary.Add(new Dictionary<string, string>() { { "1", "USA" }, { "2", "INDIA" } });
	odictionary.Add(new Dictionary<string, string>() { { "1", "USA" }, { "2", "INDIA" } });
	odictionary.Add(new Dictionary<string, string>() { { "3", "CHINA" }, { "4", "JAPAN" } });
	
	//Linq to eleminate duplicate records from dictionary
	List<Dictionary<string, string>> filteredDictionary = odictionary.GroupBy(x => string.Join("", x.Select(i => string.Format("{0}{1}", i.Key, i.Value)))).Select(x => x.First()).ToList();
	
	//Iterate each value from list of dictionaries
	foreach (var oValu in filteredDictionary)
	{
		//Casting each iteration into a dictionary
		Dictionary<string, string> cDictionary = oValu;
		//Populate result from each dictionary
		foreach (KeyValuePair<string,string> cValue in cDictionary)
		{
			Console.WriteLine(cValue.Key + cValue.Value);
		}
	}
}

Output:

1 USA
2 INDIA
3 CHINA
4 JAPAN

Leave a Reply

Your email address will not be published.