Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Binary search, IComparer, in lambda expressions style
//http://stackoverflow.com/a/4870280/579026 using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Collections.ObjectModel; using System.Collections; namespace Rextester { public class Program { public static void Main(string[] args) { List<TestClass> list = new List<TestClass>() { new TestClass() {SomeValue = 5}, new TestClass() {SomeValue = 1}, new TestClass() {SomeValue = 15}, new TestClass() {SomeValue = -10}, new TestClass() {SomeValue = 15}, new TestClass() {SomeValue = 42}, new TestClass() {SomeValue = 0} }; list = list.OrderBy(f => f.SomeValue).ToList(); Console.WriteLine(list.BinarySearch(new TestClass() {SomeValue = 15 }, new ValueComparer<TestClass>(f => f.SomeValue)));//note that it isn't the first match in the list } public class TestClass { public int SomeValue {get; set;} } } //<summary> /// Contains all of the properties of a class that /// are used to provide value semantics. ///</summary> ///<remarks> /// You can create a static readonly ValueComparer for your class, /// then call into it from Equals, GetHashCode, and CompareTo. ///</remarks> class ValueComparer<T> : IComparer<T>, IEqualityComparer<T> { public ValueComparer(params Func<T, object>[] props) { Properties = new ReadOnlyCollection<Func<T, object>>(props); } public ReadOnlyCollection<Func<T, object>> Properties { get; private set; } public bool Equals(T x, T y) { if (ReferenceEquals(x, y)) return true; if (x == null || y == null) return false; //Object.Equals handles strings and nulls correctly return Properties.All(f => Equals(f(x), f(y))); } //http://stackoverflow.com/questions/263400/263416#263416 public int GetHashCode(T obj) { if (obj == null) return -42; unchecked { int hash = 17; foreach (var prop in Properties) { object value = prop(obj); if (value == null) hash = hash * 23 - 1; else hash = hash * 23 + value.GetHashCode(); } return hash; } } public int Compare(T x, T y) { foreach (var prop in Properties) { //The properties can be any type including null. var comp = Comparer.DefaultInvariant.Compare(prop(x), prop(y)); if (comp != 0) return comp; } return 0; } } }
run
|
edit
|
history
|
help
0
6.4 Parallelism: threads and events
Generics Operator test
a5
hay
TCP
amstrong number
24 101 251 Primes
Prime
Importent Gen_Coverent Example-1
olution to problem #2 from projecteuler.net