简体   繁体   中英

Purpose of Func inside Lamda expression?

I am working on some code to get the Configuration section from the app config file. I have come across the following code in our files.

public ISection GetSection(string sectionName, System.Configuration.Configuration config)
{
  ISection section = (ISection) null;
  List<ISection> sections = this.Sections;
  if (sections != null)
    section = this.GetSectionInstance(sections.FirstOrDefault<ISection>((Func<ISection, bool>) (s => s.SectionName == sectionName)), config);
  return section;
}

private ISection GetSectionInstance(ISection freshSection, System.Configuration.Configuration config)
{
  ISection sectionInstance = (ISection) null;
  if (freshSection != null)
  {
    sectionInstance = freshSection.GetSection(config);
    sectionInstance?.CheckVersion();
  }
  return sectionInstance;
}

Question: I am not able to understand the syntax of the following line:

section = this.GetSectionInstance(sections.FirstOrDefault<ISection>((Func<ISection, bool>) (s => s.SectionName == sectionName)), config);

in the above line, I understand that in the lambda expression, we are trying to find the FirstOrDefault section which fulfills the condition s.SectionName == sectionName but I don't understand the purpose of the part (Func<ISection, bool>) . Are we trying to call a Func with signature <ISection, bool> on s where s.SectionName == sectionName ?

Looks like generated code, because there are many implicit things specified explicitly. Eg:

ISection section = (ISection) null; 

You don't need to init value with null and explicitly cast it to the ISection . Also, it's not required to specify the generic type parameter of FirstOrDefault<ISection> or explicitly specify the type of lambda - all these things will be inferred by the compiler.

Eventually, this is an equivalent of:

public ISection GetSection(string sectionName, Configuration config)
{
   var sectionInstance = this.Sections
         ?.FirstOrDefault(s => s.SectionName == sectionName)
         ?.GetSection(config);

   sectionInstance?.CheckVersion();      
   return sectionInstance;
}

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