Skip to content

Instantly share code, notes, and snippets.

@zharro
Created January 19, 2016 14:46
Show Gist options
  • Save zharro/78339bec3af4b07bf728 to your computer and use it in GitHub Desktop.
Save zharro/78339bec3af4b07bf728 to your computer and use it in GitHub Desktop.
Factory class for creating instances of IComparer (из книги Сергея Теплякова "Паттерны проектирования на платформе .NET")
using System;
using System.Collections.Generic;
namespace zharro.gists
{
class ComparerFactory
{
public static IComparer<T> Create<T>(Comparison<T> comparer)
{
return new DelegateComparer<T>(comparer);
}
private class DelegateComparer<T> : IComparer<T>
{
private readonly Comparison<T> _comparer;
public DelegateComparer(Comparison<T> comparer)
{
_comparer = comparer;
}
public int Compare(T x, T y)
{
return _comparer(x, y);
}
}
}
}
@zharro
Copy link
Author

zharro commented Jan 19, 2016

Usage of ComparerFactory:

var comparer = ComparerFactory.Create<Employee>((x, y) => x.Id.CompareTo(x.Id));
// Assuimg that SortedSet accepts only IComparable<T>
var set = new SortedSet<Employee>(comparer);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment