Skip to content

Instantly share code, notes, and snippets.

@TheWass
Last active October 27, 2016 21:40
Show Gist options
  • Save TheWass/19bbe3f07ffb6b8a1ffbfe904cbeb3b9 to your computer and use it in GitHub Desktop.
Save TheWass/19bbe3f07ffb6b8a1ffbfe904cbeb3b9 to your computer and use it in GitHub Desktop.
Useful Code snippets
//Make a dictionary of distinct records
Dictionary<int, Record> records = findRecords(keys)
.GroupBy(r => r.keyid)
.ToDictionary(g => g.Key, g => g.First());
records.TryGetValue(key, out record);
//Make groups from lines
Lines.GroupBy(l => l.ReleaseDate, (k, g) => new { Key = k, Lines = g.ToList() } ).OrderBy(g => g.Key).ToList();
// Find and remove duplicates
IEnumerable<object> duplicates = Objects
.Where(c => true) //Optional Filter
.GroupBy(c => c.keyField) //Desired field to be unique
.SelectMany(g => g.OrderBy(c => c.orderField).Skip(1)); //Field to ensure correct record is skipped
if (duplicates != null) Objects.RemoveRange(duplicates);
//Extension methods for finding max or min property.
public static T MaxBy<T, R>(this IEnumerable<T> en, Func<T, R> evaluate) where R : IComparable<R> {
return en.Select(t => new Tuple<T, R>(t, evaluate(t)))
.Aggregate((max, next) => next.Item2.CompareTo(max.Item2) > 0 ? next : max).Item1;
}
public static T MinBy<T, R>(this IEnumerable<T> en, Func<T, R> evaluate) where R : IComparable<R> {
return en.Select(t => new Tuple<T, R>(t, evaluate(t)))
.Aggregate((min, next) => next.Item2.CompareTo(min.Item2) < 0 ? next : min).Item1;
} // Usage:
list.MinBy(x => x.price);
//True when value is a representation of a number.
!isNaN(parseFloat(value)) && isFinite(value)
////AngularJS stuffs.
// Watch statement signature
$scope.$watch('', function (newValue, oldValue) { dostuff(); });
// Watch a property in an array of objects (slow, but working solution)
$scope.$watch(function($scope) {
return $scope.listOfBigObjects.map(function(bigObject) {
return bigObject.fieldICareAbout;
});
}, function(newValues, oldValues) { //You'll end up watching an array of properties.
dostuff();
}, true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment