I wrote something that has probably done thousands of times: a function that takes a parsed http query as input and return a linq query.
Any input is appreciated.
public IList<Lead> GetLeads(NameValueCollection nvc)
{
IQueryable<MyContext> queryBase = QueryBase();
foreach (string key in nvc)
{
const string format = "dd-MM-yyyy";
if (nvc[key] == "all")
continue;
//case where an array of possible values is sent
const string regex = "\\[.*\\]";
Expression<Func<MyContext, bool>> predicate = c => false;
string[] values = nvc[key].Split(',');
foreach (string value in values)
{
Expression<Func<MyContext, bool>> predicateTemp;
DateTime date;
switch (Regex.Replace(key, regex, ""))
{
case "nature":
string value1 = value;
predicateTemp =
c => c.Typologies.NatureDemande == value1;
break;
case "departementCode":
string value2 = value;
predicateTemp = c => c.Geographies.DepartementCode == value2;
break;
case "start":
String start = value;
date = DateTime.ParseExact(start, format, null);
DateTime date1 = date;
predicateTemp = c => c.Temps.Date >= date1;
break;
case "end":
String end = value;
date = DateTime.ParseExact(end, format, null);
DateTime date2 = date;
predicateTemp = c => c.Temps.Date <= date2;
break;
default:
predicateTemp =
c => true;
break;
}
predicate = OrElse(predicate, predicateTemp);
}
queryBase = queryBase.Where(predicate);
}
//query all leads
IQueryable<Lead> query = (from x in queryBase
select new Lead
{
id = Convert.ToInt32(x.Leads.DemandeWeb_FK),
lng = Convert.ToDouble(x.Leads.longitudeClient.Replace(",", ".")),
lat = Convert.ToDouble(x.Leads.latitudeClient.Replace(",", ".")),
temps = Convert.ToInt32(x.Leads.GeolocDureeTrajetDistrib),
distance = Convert.ToInt32(x.Leads.GeolocDistanceRouteDistrib),
nature = x.Typologies.NatureDemande,
type = x.Distributeurs.DistribType,
reseau = x.Distributeurs.ReseauDistributeur,
instance = x.Demands.IdInstance,
distribution = Convert.ToInt32(x.Distributeurs.DistribIdPointDeVente),
});
return query.ToList();
}
strings? This is especially problematic for thedoubles, since theReplace()indicates there is some culture mismatch. \$\endgroup\$