Improving IEnumerable<T> LINQ query

Total Post:135


 2032  View(s)
Rate this:
Hi Expert! 

Starting with the next entities definition:

Public Class Certificate{
  public  ID as int;

Public Class Authority{
  ID int;
  Certificates IEnumerable<Certificate>;
My function recives 2 collections: IEnumerable<Certificate> and IEnumerable<Authority>. I need to select the Authorities which Certificates collection has at least 

one Certificate in the IEnumerable<Certificate> input parameter.

My firt implementation is enumerating the IEnumerable<Certificate> and selecting the Authority using a Where(predicate).

Public IEnumerable<Authority> SelectAuthorities(authList IEnumerable<Authority>, certList IEnumerable<Certificate>){

  foreach (Certificate loadedCert in certList) {
    yield return auth.Where(a => a.Certificados.Any(c1 => c1.IDCert == loadedCert.IDCert));

I think there must be a way to avoid the for loop using a more complex linq correlated subquery (I feel it in the "force") but I can't find it.

Can anybody help?
Thanks in advance! 
  1. Re: Improving IEnumerable<T> LINQ query

    Hi Chintoo!

    You can use double Any to avoid loop:

    authList.Where(a => a.Certificados.Any(c1 => certList.Any(c2 => c1.IDCert == c2.IDCert)));

    I Hope it helpful to you.


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.