Home > Software engineering >  How to find duplicate parameter and consider one which contains value in C#
How to find duplicate parameter and consider one which contains value in C#

Time:11-21

I would like to find duplicate parameters and then consider the one which has value and eliminate the one which does not contain value.

Suppose I have parameters like firstname, lastname, firstname and the value is like firstname=, lastname=con, firstname=abc

decryptedRequest is something like

lastname=con&firstname=&firstname=abc

   private NameValueCollection parameters;
            
    foreach (var parameter in parameters)
    {
                            
        if (IsDuplicatedParam(parameter.ToString(), decryptedRequest))
        {
           LogManager.Publish(LogTypes.Exception | LogTypes.Error, "Duplicate parameter "   parameter   " received in request : "   decryptedRequest);
                    return false;
         }           
    }
            
    private bool IsDuplicatedParam(string parameter, string decryptedRequest)
    {       
        var requestWithoutParameter = decryptedRequest.Replace(parameter   "=", "");
        if (decryptedRequest.Length - requestWithoutParameter.Length > parameter.Length   1)
            return true;
            return false;
    }

Expected output should be, lastname=con, firstname=abc

CodePudding user response:

Try this:

parameters.Add("firstname", "");
parameters.Add("lastname", "bbb");
parameters.Add("firstname", "ccc");

IEnumerable<string> pairs =
    from key in parameters.Cast<String>()
    from value in parameters.GetValues(key).Where(x => x != "").Take(1)
    select $"{key}={value}";

Console.WriteLine(String.Join("&", pairs));

That outputs firstname=ccc&lastname=bbb.

CodePudding user response:

you could implement like this.

string str = "lastname=con&firstname=&firstname=abc";
var arr = str.Split('&');
Dictionary<string, string> dict = new Dictionary<string, string>();
for (int i = 0; i < arr.Length; i  )
{
    int index = arr[i].IndexOf('=');
    string item = arr[i].Substring(0, index);

    if (dict.ContainsKey(item) == false)
    {
        string value = arr[i].Substring(index);
        if (value != "=")
            dict.Add(item, value);
    }
}

It will give you a dictionary with keys as firstname and =con as value. you could modify the cod eif you want to get rid of = in the value

  •  Tags:  
  • c#
  • Related