User Id :    Password :      New Member   Forgot Password  
 
Difference between SkipWhile and Where in linq
Description Before some time I have written a blog post about the SkipWhile operator and a reader of my blog asked me that we can do the same thing with Where also but there is a difference between this two. So In this post I am going to explain you difference between those two.   No. of Views     2960
  Rating     0
Author Jalpesh Vadgama   Posted On     17 May 2012
Tags C#,LINQ,LINQ Basic,C# 4.0,C# : How To,LINQ : How To    

Sample Code   Download Code

Where operator filters a list of collection based on condition. It will filter whole collection while SkipWhile will only skip those elements in list until condition is true and after that it will stop filtering of skipping. Now let’s take an example where we can see the difference between Where and SkipWhile. Following is a code for that.

 

using System;
using System.Collections.Generic;
using System.Linq;
namespace Linq
{
  class Program
  {
      static void Main(string[] args)
      {
          string[] names = { "Jalpesh", "Jayesh", "Tushar", "Tejas", "Sanjay", "Nijesh","Jemit","Jay" };
 
          Console.WriteLine("Skipwhile Operator");
          foreach (var name in names.SkipWhile(s => s.ToLower().StartsWith("j")))
          {
              Console.WriteLine(name);
          }
          Console.WriteLine("-----------------------------------");
          Console.WriteLine("Where Operator");
          foreach (var name in names.Where(s => !s.ToLower().StartsWith("j")))
          {
              Console.WriteLine(name);
          }
      }
  }
}

 

As you can see that in the above code I have a string array called names where I have people’s name as string. Here you can see there are multiple names start with letter “J” in array. Now once we use SkipWhile operator it will skip the elements untill condition is false for first time So it will skip the elements until condition satisfied for the first once you have different condition it will not going skip element even if they are satisfying the condition. While in where it will filter whole collection and print output.

Let’s run above example. Following is a output as expected.

 

 

That’s it. Hope you like it. Stay tuned for more. Till than happy programming.

About Author

About Author I am jalpesh vadgama an Microsoft MVP for Visual C# and BrainBench Certified ASP.NET Developer having more then 5 years of experience in .NET Technology.Please feel free to contact me for any queries via posting comments on my blog I will try to reply as early as possible. Please also visit my blog at http://jalpesh.blogspot.com/ Jalpesh Vadgama
No Photo
 
Country India
Company N/A
Home Page http://jalpesh.blogspot.com/

Rate this article

Rating options from poor, fair, good, very good to excelent.  
 

Comments

   
Write your comment here.
Comment
Verification Code