I get a List<KeyValuePair<Parameter, string>>
(Parameter is an Enum). Now I always get 15 of these ListItems, those who are not needed are null or empty. With these values (string part of the pair) I have to fill different api queries. Respectivly to the api endpoints some of the values are named differently, but are the same value. So I would have to change some of the values. I did it this way till now:
public void CreateRequest(ApiEndpoints endpointType, string endpointName, List<KeyValuePair<Parameters, string>> parameters)
{
List<KeyValuePair<string, string>> parameterList = new List<KeyValuePair<string, string>>();
switch(endpointType)
{
case ApiEndpoints.Model:
string modelId = parameters.Where(k => k.Key == Parameters.Model).Select(k => k.Value).FirstOrDefault();
if(!string.IsNullOrWhiteSpace(modelId))
{
parameterList.Add(new KeyValuePair<string, string>("id", modelId));
}
break;
case ApiEndpoints.Group:
string groupId = parameters.Where(k => k.Key == Parameters.Group).Select(k => k.Value).FirstOrDefault();
modelId = parameters.Where(k => k.Key == Parameters.Model).Select(k => k.Value).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(groupId))
{
parameterList.Add(new KeyValuePair<string, string>("id", groupId));
}
if (!string.IsNullOrWhiteSpace(modelId))
{
parameterList.Add(new KeyValuePair<string, string>("modelId", modelId));
}
break;
...
}
}
private string QueryBuilder(List<KeyValuePair<string, string>> parameters)
{
string query = string.Empty;
bool firstItem = true;
foreach(var parameter in parameters)
{
if (firstItem)
{
query += "?";
firstItem = false;
}
else
{
query += "&";
}
query += parameter.Key + "=" + parameter.Value;
}
return query;
}
That is partly necessary because the modelId sometimes is used as "id" and sometimes as "modelId", depending on the endpoint.
As you can see, the parameter handling is getting fast voluminous. Some endpoints are having up to 8 optional parameters. And we are (till now) at 21 endpoints. But there are coming more. So it will get really unclear to overlook this code. Has someone an idea how to shorten/flatten this code? (The 15 KeyValuePairs are fix. I cannot change that. Only my handling.
Is it maybe possible to change the string inside a .Select in the lambda expression? That way every parameter would be reduced to one line.
I'm not sure I understand the problem completely, but if it's the readability of the CreateRequest code, you could always create a helper function, for instance AddParamIfFound and do:
case ApiEndpoints.Model:
AddParamIfFound(parameterList, parameters, "id", Parameters.Model);
break;
case ApiEndpoints.Group:
AddParamIfFound(parameterList, parameters, "id", Parameters.Group);
AddParamIfFound(parameterList, parameters, "modelId", Parameters.Model);
break;
AddParamIfFound should be trivial to implement by refactoring your existing code.