Home > DeveloperSection > Forums > Improving IEnumerable<T> LINQ query
Chintoo Semi

Total Post:135

Posted on    May-13-2013 2:48 AM

 C# C# 

 1 Reply(s)
 1548  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! 


Total Post:604

Posted on    May-13-2013 9:31 AM

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.

Don't want to miss updates? Please click the below button!

Follow MindStick