Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between `where` in the query object and `if` in the extension methods

I am studying LINQ.

I don’t know the difference between using if in extension method and using where in query object.

The Console.WriteLine() results are the same, is there any difference in speed?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If you think about it, there seems to be a difference in readability, but that’s my guess.

To be honest, I know it’s a useless curious, but I was so curious about it, so I wrote it.

We look forward to hearing from you.

Oh, if there is anything in the article that needs to be improved, please advise.

...

public static IEnumerable<Student> GetTeenAgerStudents(this IEnumerable<Student> source)
{
  foreach (Student std in source)
  {
    yield return std;
  }
}

...

var teenAgerStudents = from s in studentList.GetTeenAgerStudents()
                       where s.Age >= 10 && s.Age < 20
                       select s;
...

public static IEnumerable<Student> GetTeenAgerStudents(this IEnumerable<Student> source)
{
  foreach (Student std in source)
  {
    if (std.Age >= 10 && std.Age < 20)
          yield return std;
  }
}

...

var teenAgerStudents = from s in studentList.GetTeenAgerStudents()
                       select s;

The above code is referenced from https://www.tutorialsteacher.com/linq/linq-deferred-execution.

>Solution :

I prediction the exact speed difference between them. if is faster. But for legibility reasons, where is the most commonly used route. You can understand where like a sql query. Here, it filters some data from the data collection and reveals the ones that are suitable for you. Looks like T-Sql.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading