IMPROVING IENUMERABLE<T> LINQ QUERY

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
C# 
C#
 1615  View(s)
Ratings:
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. AVADHESH PATEL

    Post:604

    Points:4228
    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!