Complex linq query when passing parameters

2

I need to do a linq query, but I'm having a hard time doing it. I have 5 filters on the page. Being that three of them come from three dropdown (select). I can only consider select, if the text in them are different from "NO FILTER", first step. The last select, has only two lines, being the first GENERAL and the second SOUZA CRUZ. If it is general, it must bring everything that is in the field of vision, if not only that which is the cross. Since I can not give an if inside a linq, I get this difficulty. I have this query, that a colleague passed me here in this forum, that way, but I find it difficult to put more filters in my new context. The query that Morrison gave me was this one and answered what I requested.

.Where(cn => (cn.x1.a1.o2.NumOs == Convert.ToInt32(_osparceiro)) && (_cnpj == "" || cn.cnpj == _cnpj))

Now I'm having trouble making mine. See my method:

[HttpPost]
        public JsonResult MontaResultadoPdv(string _cnpj, string _contato, string _filtrarrede, string _filtarstatus, string _visao)
        {
            V99_WEBEntities db = new V99_WEBEntities();

            var resultadopdv = (from pdv in db.T_PDV
                                    .Where(res => (res.CNPJ == "" || res.CNPJ == _cnpj))
                                select new { 
                                            pdv.RazaoSocial,
                                            pdv.}).ToList(); 

            return Json(new {  }, JsonRequestBehavior.AllowGet);
        }

These are the parameters that come from the selects:

string _filtrarrede, string _filtarstatus, string _visao

If you see null or empty, for example, the query will give me an unexpected result.

    
asked by anonymous 26.06.2014 / 14:17

1 answer

3

If I understand correctly, maybe this will help you:

var resultadopdv = (from pdv in db.T_PDV
            .Where(res => (res.CNPJ == "" || res.CNPJ == _cnpj))
        select new { 
                    pdv.RazaoSocial,
                    pdv.});

if(!string.IsNullOrEmpty(_filtrarrede))
    resultadopdv = resultadopdv.Where(e => e.rede == _filtrarrede);
if(!string.IsNullOrEmpty(_filtarstatus))
    resultadopdv = resultadopdv.Where(e => e.status == _filtarstatus);
if(!string.IsNullOrEmpty(_visao))
    resultadopdv = resultadopdv.Where(e => e.visao == _visao);

return Json(resultadopdv.ToList(), JsonRequestBehavior.AllowGet);
    
26.06.2014 / 14:50