Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of KeyValuePair to be Distinct

I have a list of KeyValuePair which its values are list too such as

List<KeyValuePair<string, List<string>>> ListX = new List<KeyValuePair<string,List<string>>>();
ListX.Add(new KeyValuePair<string,List<string>>("a",list1));
ListX.Add(new KeyValuePair<string,List<string>>("b",list1));
ListX.Add(new KeyValuePair<string,List<string>>("a",list1));`

I want the keys of each KeyValuePair in the list to be not duplicated, only the keys, can I use Distinct in this list?

for example I want the third item in the list that has "a" key to be deleted because it's duplicated.

like image 405
user1947393 Avatar asked Sep 04 '25 03:09

user1947393


1 Answers

Though it is possible to work around with your current List to make it having Distinct keys, the simplest solution which I think fit for your case is to use Dictionary<string,List<string>>

It does just exactly what you need:

Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
dict.Add("a", new List<string>());
dict.Add("b", new List<string>());
dict.Add("a", new List<string>()); //will throw an error

Image:

enter image description here

If you need to check if a Key is already exist when you want to add a <Key,Value> to a your dictionary, simply check by ContainsKey:

if (dict.ContainsKey(key)) //the key exists
like image 140
Ian Avatar answered Sep 06 '25 22:09

Ian