Wilsonhut

Deal with it or don't

Sift

So the Except linq Extension method effectively does a Distinct on your list. I wanted it to leave my list alone, other than removing the matching items from the other list, of course.

I called it Sift. Here it is:

public static IEnumerable Sift(this IEnumerable enumerable, IEnumerable other)
{
  var otherList = new HashSet(other);
  return enumerable.Where(item => !otherList.Contains(item));
}

BTW – The HashSet’s Contains method is WAAAY faster than an array’s Contains method.

Here’s an example of how to use it:
Suppose you have string, and you want to create a file using that string as the name, but you want the name to only use acceptable characters…

It’d be nice to have a method on a string that would turn it into a File Name-Friendly string…

public static string ToFileNameFriendlyString(this string value)
{
  return new string(value.ToCharArray().Sift(Path.GetInvalidFileNameChars()).ToArray());
}

Then you would call it like so:

var fileName = "2010/07/12".ToFileNameFriendlyString();

fileName would then contain “20100712”

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: