Search code examples
c#distinctnamevaluecollection

c# NameValueCollection distinct values


C# code as below:

NameValueCollection nvc = new NameValueCollection();
nvc.Add("color", "red");
nvc.Add("size", "s");
nvc.Add("color", "red");
nvc.Add("size", "m");
nvc.Add("color", "red");
nvc.Add("size", "l");

//blue
nvc.Add("color", "blue");
nvc.Add("size", "m");
nvc.Add("color", "blue");
nvc.Add("size", "l");
//green
nvc.Add("color", "green");
nvc.Add("size", "s");
nvc.Add("color", "green");
nvc.Add("size", "m");
nvc.Add("color", "green");
nvc.Add("size", "l");

actual result:

color:red,red,red,blue,blue,green,green,green 
size:s,m,l,m,l,s,m,l 

hope result:

color:red,blue,green     
size:s,m,l 

Solution

  • I'm not sure on your use case, NameValueCollection allows duplicates better to use Dictionary for such cases.

    Still you could do something like this on NameValueCollection to get the results you want.

    var results = nvc.AllKeys
        .GroupBy(g=>g)
        .Select(s=> 
                new 
                {
                    key = s.Key,  
                    values = nvc.GetValues(s.Key).Distinct() 
                }); 
    
    
    foreach(var result in results)
    {
        Console.WriteLine("{0}- {1}", result.key, string.Join(",", result.values) ;
    }
    

    Working Example