Sphyrnidae Common Library
2.0.1
Shared Utilities/Library
|
A binary list is a ReadOnlyCollection that gives a huge performance boost for searching for items. C# does have a list method called BinarySearch(), but this still requires the following to use:
This BinaryList provides this ability (and new abilities) in a much cleaner way. First, you must have an IEnumerable. Then you call the extension method ToBinaryList() (see ListExtensions). This converts the IEnumerable to a ReadOnlyCollection where you can perform Binary Searches (or any other methods on the ReadOnlyCollection).
The conversion method requires you to specify the "keySelector". This is a lamba expression which selects the item in the list (eg. x => x.myField). The field in the list must be an IComparable. The binary list will automatically sort on that field so that all method calls will work against the already ordered list.
Methods:
By calling the ToCaseInsensitiveBinaryList() method on a list (see ListExtensions), this creates a CaseInsensitiveBinaryList. This class is a specific instance of the BinaryList where the keySelector must point to a field that is of type string. The resulting class will allow the same actions as BinaryList, but comparisons will be done case-insensitive. Eg. "AbC" matches "abc".
If your IEnumerable contains strings (as opposed to a class with fields), then you should call the ToCaseInsensitiveBinaryList() method without a keySelector.
var stringList = new List<string> { "A", "b", "C" }; var binaryList = stringList.CaseInsensitiveBinaryList(); binaryList.FindBinary("a"); // => "A" var widgetList = new List<Widget> { new Widget { Id = 1, Name = "foo" }, new Widget { Id = 2, Name = "foo" }, new Widget { Id = 3, Name = "foo2" } }; var binaryWidgetList = widgetList.ToBinaryList(x => x.Name); var matchedItems = binaryWidgetList.FindBinaryList("foo"); // 2 Widgets are returned in a list