Project Description
create anonymous IComparer<T>/IEqualityComparer<T> by lambda expression. This is replacement for Linq standard query operator's IComparer<T>/IEqualityComparer<T> overload.
  • How To Use
var comparer = AnonymousComparer.Create(compareKeySelector);
or use added Standard Query Operator's Extension Methods
  • Example
class MyClass
{
    public int MyProperty { get; set; }
}

static void Main()
{
    // for example.
    var mc1 = new MyClass { MyProperty = 3 };
    var mc2 = new MyClass { MyProperty = 3 };
    var array = new[] { mc1, mc2 };

    array.Distinct().Count(); // 2
    array.Distinct(mc => mc.MyProperty).Count(); // 1
    // full write.
    array.Distinct(AnonymousComparer.Create((MyClass mc) => mc.MyProperty));

    // example2, with anonymous type sequence
    var anonymous = new[] 
    {
        new { Foo = "A", Key = 10 },
        new { Foo = "B", Key = 15 }
    };
    anonymous.Contains(new { Foo = "dummy", Key = 10 }, a => a.Key); // true
}
  • ver1.1 - Add: Full IEqualtyComparer<T> overload
var myClassComparer = AnonymousComparer.Create<MyClass>(
    (x, y) => x.MyProperty == y.MyProperty, // Equals
    obj => obj.MyProperty.GetHashCode()); // GetHashCode
  • ver1.2 - can create anonymous IComparer<T>
var seq = new[] { 1, 2, 3 };
// Create IComparer<T>
var comparer = AnonymousComparer.Create<int>((x, y) => y - x);
seq.OrderBy(x => x, comparer);
// OrderBy/ThenBy Extension Methods
seq.OrderBy(x => x, (x, y) => y - x); // 3, 2, 1
seq.OrderByDescending(x => x, (x, y) => y - x); // 1, 2, 3

author's other linq project

Last edited Sep 21, 2011 at 9:32 PM by neuecc, version 10