Roberto Mindoli Roberto Mindoli - 3 months ago 14
C# Question

C# query only when textbox is edited

I have a query that work on a great data table. The code for the query is:

var getExtInv = snd.external_invoices.OrderByDescending(x => x.date).ToList();
var query = (from c in getExtInv
join o in snd.invoices on c.idexternal_invoices equals o.id_external_invoice
select new {c.idexternal_invoices,
c.businessname,
o.number,
c.message,
c.price,
c.date,
c.tipologiaPagamento,
c.esitoPagamento,
c.iduser
}).ToList();


I need to filter this query with a number of textbox value that can be empty. An example for one search filter is:

if (txtIdUser.Text != "")
{
int idUserSel = Convert.ToInt32(txtIdUser.Text);
query = query.Where(x => x.iduser == idUserSel).ToList();
}


the problem is that with this approach initially load a very high number of data which then filter based on the presence or absence of textfield filled. In doing so the initial loading time is very long. How can I speed up the process?

Thanks to all

Answer

As mentioned, don't use .ToList, .ToArray, .Count, etc. before you are ready to use the results.

int i = 0; 
var query = from c in snd.external_invoices.OrderByDescending(x => x.date)
            join o in snd.invoices on c.idexternal_invoices equals o.id_external_invoice
            select new {c.idexternal_invoices, c.businessname, o.number, c.message,
                        c.price, c.date, c.tipologiaPagamento, c.esitoPagamento, c.iduser };

if(int.TryParse(txtIdUser.Text, out i) // this will check if text is not empty and valid int
    query = query.Where(x => x.iduser == i);

and at the end when you are ready to use the results:

var results = query.ToList();