Skip to content

Instantly share code, notes, and snippets.

@casparkleijne
Created August 9, 2011 21:15
Show Gist options
  • Save casparkleijne/1135221 to your computer and use it in GitHub Desktop.
Save casparkleijne/1135221 to your computer and use it in GitHub Desktop.
Add Some Yoda to your linq
using System;
using System.Collections.Generic;
using System.Linq;
namespace Dagobah.System
{
public static class Yoda
{
public static bool IHave<T>(this IEnumerable<T> source, T value)
{
return source.Contains(value);
}
public static bool IHave<T>(this IEnumerable<T> source, T value, IEqualityComparer<T> comparer)
{
return source.Contains(value, comparer);
}
public static bool YouMust<T>(this IEnumerable<T> source, Func<T,bool> predicate)
{
return source.All(predicate);
}
public static T InThisOne<T>(this IEnumerable<T> source)
{
return source.FirstOrDefault();
}
public static T InThisOne<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
return source.FirstOrDefault(predicate);
}
public static IEnumerable<TResult> YouBe<T,TResult>(this IEnumerable<T> source)
{
return source.Cast<TResult>();
}
}
}
// usage:
using System.Linq;
using Dagobah.System;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var t = numbers
.Select(x => x * 2)
.YouMust(x => x < 7); // <-- AWESOME!!!
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment