简体   繁体   中英

How to improve Query with linq

I'm a little bit stuck, I took an new project but there is so timeout issue due to queries.

I don't know the syntax in linq to improve one querie even if i tried multiple times.

The query is :

var contactslist = (User as CustomPrincipal).contacts;

            var contacts = from m in db.ADDR_DEST.toList()
                           from n in contactslist
                           where m.ADDR_COUNTRY == n.country &&  m.ADDR_TPL_TYPE   == n.tpl_type
                           select m;

But I want to dosen't launch this query before that i had different parametre so i remove the .toList() for adding some condition with

contacts.where(..);

And then I would like launch my query but i got an error with the type which must be an list<> but in this case it's a Iqueryable.

Can you help me please? Is there an other way to launch this query after I do all my settings?

Try (not tested):

var contacts = db.ADDR_DEST.Where(m => m.COUNTRY == contactslist.country
                                  && m.ADDR_TPL_TYPE == contactslist.tpl_type)
                            .ToList();

If contactslist is a list then try the following

var contacts = (from addr in db.ADDR_DEST
                join cl in contactslist on
                   new {addr.COUNTRY, addr.ADDR_TPL_TYPE} equals new {cl.country, cl.tpl_type}
                select new {addr})
                .ToList();

The Linq join is easier to understand than its lambda equivalent!

There are some good examples here

You can do something like that:

db.ADDR_DEST.Join(contactslist, 
                  addr => new { country = addr.ADDR_COUNTRY, type = addr.ADDR_TPL_TYPE }, 
                  cont => new { country = cont.country, type = cont.tpl_type }, 
                  (addr, cont) => addr)
            .ToList();

Then, if you want to choose the contactlist that meet certain requirements:

db.ADDR_DEST.Join(contactslist.Where(...).ToList(), 
                  addr => new { country = addr.ADDR_COUNTRY, type = addr.ADDR_TPL_TYPE }, 
                  cont => new { country = cont.country, type = cont.tpl_type }, 
                  (addr, cont) => addr)
            .ToList();

I hope you find it useful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM