Tuesday, April 17, 2012

Difference between SkipWhile and Where in linq

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.

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.

image

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

Shout it

kick it on DotNetKicks.com
Share:

1 comment:

  1. Great Article related to linq :)

    We can also submit our .net related links on http://www.dotnettechy.com to improve traffic.

    The dotnettechy.com is a community of .Net developers joined together to learn, to teach, to find solutions, to find interview questions and answers, to find .net website / blog collection and to have fun programming. 

    ReplyDelete

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews