public static void MinBy_Generic_NullSource_ThrowsArgumentNullException() { IEnumerable <int> source = null; AssertExtensions.Throws <ArgumentNullException>("source", () => source.MinBy(x => x)); AssertExtensions.Throws <ArgumentNullException>("source", () => source.MinBy(x => x, comparer: null)); AssertExtensions.Throws <ArgumentNullException>("source", () => source.MinBy(x => x, Comparer <int> .Create((_, _) => 0))); }
public static void MinBy_Generic_NullKeySelector_ThrowsArgumentNullException() { IEnumerable <int> source = Enumerable.Empty <int>(); Func <int, int> keySelector = null; AssertExtensions.Throws <ArgumentNullException>("keySelector", () => source.MinBy(keySelector)); AssertExtensions.Throws <ArgumentNullException>("keySelector", () => source.MinBy(keySelector, comparer: null)); AssertExtensions.Throws <ArgumentNullException>("keySelector", () => source.MinBy(keySelector, Comparer <int> .Create((_, _) => 0))); }
public static (Point, Point, Point, Point) SortCorners(this IEnumerable <Point> corners) { var tl = corners.MinBy(pt => pt.X + pt.Y); // top left var br = corners.MaxBy(pt => pt.X + pt.Y); // bottom right var tr = corners.MaxBy(pt => pt.X - pt.Y); // top right var bl = corners.MinBy(pt => pt.X - pt.Y); // bottom left return(tl, tr, br, bl); }
public void MinByOnNullEnumerableThrowsArgumentNullException() { IEnumerable <int> sut = null; var ex = Assert.Throws <ArgumentNullException>(() => sut.MinBy(i => i)); Assert.Equal("source", ex.ParamName); var ex2 = Assert.Throws <ArgumentNullException>(() => sut.MinBy(i => i, Comparer <int> .Default)); Assert.Equal(ex.ParamName, ex2.ParamName); }
/// <summary> /// Quantifies the heatmap values to the nearest value in the supplied array /// </summary> /// <param name="Quantifications"></param> public void Quantify(IEnumerable <int> Quantifications) { for (int X = 0; X < _Map.Length; X++) { _Map[X] = Quantifications.MinBy(Q => Math.Abs(Q - _Map[X])); } }
public void Test_Empty_MinBy() { IEnumerable <MyObject> res = Enumerable.Empty <MyObject>(); MyObject mo = res.MinBy(); mo.Should().BeNull(); }
/// <summary> /// Returns the elements with the minimum key value by using the specified comparer to compare key values. /// </summary> /// <typeparam name="TSource">Source sequence element type.</typeparam> /// <typeparam name="TKey">Key type.</typeparam> /// <param name="source">Source sequence.</param> /// <param name="keySelector">Key selector used to extract the key for each element in the sequence.</param> /// <param name="comparerFactory">The definition of a comparer to compare keys.</param> public static IList <TSource> MinBy <TSource, TKey>(this IEnumerable <TSource> source, Func <TSource, TKey> keySelector, Func <ComparerBuilderFor <TKey>, IFullComparer <TKey> > comparerFactory) { _ = comparerFactory ?? throw new ArgumentNullException(nameof(comparerFactory)); var comparer = comparerFactory(ComparerBuilder.For <TKey>()); return(source.MinBy(keySelector, comparer)); }
public void Test_Null_MinBy() { IEnumerable <MyObject> res = null; Action ac = () => res.MinBy(); ac.Should().Throw <ArgumentNullException>(); }
public static void BestThingRequestGroup() { DebugTables.MakeTablesDialog(from x in DefDatabase <ThingDef> .AllDefs where ListerThings.EverListable(x, ListerThingsUse.Global) || ListerThings.EverListable(x, ListerThingsUse.Region) orderby x.label select x, new TableDataGetter <ThingDef>("defName", (ThingDef d) => d.defName), new TableDataGetter <ThingDef>("best local", delegate(ThingDef d) { IEnumerable <ThingRequestGroup> source2 = ListerThings.EverListable(d, ListerThingsUse.Region) ? ((ThingRequestGroup[])Enum.GetValues(typeof(ThingRequestGroup))).Where((ThingRequestGroup x) => x.StoreInRegion() && x.Includes(d)) : Enumerable.Empty <ThingRequestGroup>(); if (!source2.Any()) { return("-"); } ThingRequestGroup best2 = source2.MinBy((ThingRequestGroup x) => DefDatabase <ThingDef> .AllDefs.Count((ThingDef y) => ListerThings.EverListable(y, ListerThingsUse.Region) && x.Includes(y))); return(best2 + " (defs: " + DefDatabase <ThingDef> .AllDefs.Count((ThingDef x) => ListerThings.EverListable(x, ListerThingsUse.Region) && best2.Includes(x)) + ")"); }), new TableDataGetter <ThingDef>("best global", delegate(ThingDef d) { IEnumerable <ThingRequestGroup> source = ListerThings.EverListable(d, ListerThingsUse.Global) ? ((ThingRequestGroup[])Enum.GetValues(typeof(ThingRequestGroup))).Where((ThingRequestGroup x) => x.Includes(d)) : Enumerable.Empty <ThingRequestGroup>(); if (!source.Any()) { return("-"); } ThingRequestGroup best = source.MinBy((ThingRequestGroup x) => DefDatabase <ThingDef> .AllDefs.Count((ThingDef y) => ListerThings.EverListable(y, ListerThingsUse.Global) && x.Includes(y))); return(best + " (defs: " + DefDatabase <ThingDef> .AllDefs.Count((ThingDef x) => ListerThings.EverListable(x, ListerThingsUse.Global) && best.Includes(x)) + ")"); })); }
public void StartTiming(bool startOnMovement = true) { if (geolocator == null) { throw new InvalidOperationException("LapTimer must be initialized before calling StartTiming."); } if (isTiming) { StopTiming(); } lapNumber = 1; lapStartElapsedTime = TimeSpan.Zero; headingNormalisation = new List <double>(); lapCoordinates = new List <LapDataPointViewModel>(); currentSector = generateSectors ? null : sectorCoordinates.MinBy(s => s.SectorNumber); accelerometer = Accelerometer.GetDefault(); if (accelerometer != null) { accelerometer.ReadingChanged += accelerometer_ReadingChanged; } geolocator.PositionChanged += geolocator_PositionChanged; if (!startOnMovement) { stopwatch.Start(); isTiming = true; if (TimingStarted != null) { TimingStarted(this, null); } } isFirstReading = true; }
public void Test_MinBy_NullSourceThrowsException() { // Arrange. IEnumerable <TestContainer <int> > items = null; // Act/Assert. Assert.Throws <ArgumentNullException>(() => items.MinBy(item => item.Item)); }
public static List <BarRequiredArea> MinBarRequiredArea(this IEnumerable <BarRequiredArea> results) { if (results.IsNullOrEmpty() || results.Any(x => x.IsNull())) { return(null); } List <BarRequiredArea> minResults = new List <BarRequiredArea>(); minResults.Add(results.MinBy(x => x.Top)); minResults.Add(results.MinBy(x => x.Bottom)); minResults.Add(results.MinBy(x => x.Perimeter)); minResults.Add(results.MinBy(x => x.Shear)); minResults.Add(results.MinBy(x => x.Torsion)); return(minResults); }
public Time DecideMinTime(IEnumerable <Time> g) { if (g == null) { throw new ArgumentNullException("g"); } return(g.MinBy(i => timeOrderingMap[i])); }
public static Person GetNearest(Person myself, IEnumerable <Person> persons) { if (!persons.Any()) { return(null); } return(persons.MinBy(x => (x.transform.position - myself.transform.position).sqrMagnitude)); }
public static TKey MinValue <TSource, TKey>(this IEnumerable <TSource> source, Func <TSource, TKey> selector, TKey defaultValue) { if (source == null || !source.Any()) { return(defaultValue); } return(selector(source.MinBy(selector))); }
/// <summary> /// Generates a copy of the heatmaps, quantized to the given enum values /// </summary> /// <typeparam name="T"></typeparam> /// <param name="Quantifications"></param> /// <returns></returns> public T[] MapQuantify <T>(IEnumerable <MapQuantification <T> > Quantifications) { T[] QuantifiedMap = new T[_Map.Length]; for (int X = 0; X < _Map.Length; X++) { QuantifiedMap[X] = Quantifications.MinBy(Q => Math.Abs(Q.Value - _Map[X])).Quantification; } return(QuantifiedMap); }
public static Construct Shallowest(this IEnumerable <Construct> cons) { if (cons.IsEmpty()) { return(null); } return(cons.MinBy(c => c.Depth).First()); }
public void MinBy_Throws_If_Source_Is_Null() { IEnumerable <Foo> source = null; // ReSharper disable once AssignNullToNotNullAttribute // ReSharper disable once ReturnValueOfPureMethodIsNotUsed var ex = Assert.Throws <ArgumentNullException>(() => source.MinBy(_getFooValue)); ex.ParamName.Should().Be("source"); }
public int Part1() { var leastZerosLayer = _layers.MinBy(layer => layer.Count(c => c == '0')).First().ToArray(); var onesCount = leastZerosLayer.Count(c => c == '1'); var twosCount = leastZerosLayer.Count(c => c == '2'); return(onesCount * twosCount); }
public static T MaxBy <T>(this IEnumerable <T> @this, IComparer <T> comparer = null) where T : class { if (comparer == null) { comparer = Comparer <T> .Default; } return(@this.MinBy(comparer.Revert())); }
private void SaveFlatSeries(IEnumerable <Flat> flats) { var flatSeries = new FlatSeries(); flatSeries.Amount = flats.Count(); flatSeries.AvgPrice = flats.Average(x => x.TotalPrice); flatSeries.AvgPricePerMeter = flats.Average(x => x.Surface) == 0 ? 0 : flatSeries.AvgPrice / flats.Average(x => x.Surface); flatSeries.BestValueId = flats.MinBy(x => x.Surface == 0 ? 0 : (x.TotalPrice / x.Surface)).FirstOrDefault()?.Id; flatSeries.BiggestId = flats.MaxBy(x => x.Surface).FirstOrDefault()?.Id; flatSeries.MostExpensiveId = flats.MaxBy(x => x.TotalPrice).FirstOrDefault()?.Id; flatSeries.SmallestId = flats.MinBy(x => x.Surface).FirstOrDefault()?.Id; flatSeries.CheapestId = flats.MinBy(x => x.TotalPrice).FirstOrDefault()?.Id; flatSeries.DateFetched = DateTime.Now.Date; _otoDomRepository.AddFlatSeries(flatSeries); }
public LoadIncrementalState SelectDisplacement( StructureInfo info , LoadState state , LoadIncrementalState prediction , IEnumerable <LoadIncrementalState> candidates) { double Function(LoadIncrementalState candidate) => prediction.IncrementDisplacement.DotProduct(candidate.IncrementDisplacement) / (prediction.IncrementDisplacement.Norm(2) * candidate.IncrementDisplacement.Norm(2)); return(candidates.MinBy(Function).First()); }
private static ISignature FromOverloads(Parameter[] allParameters, Overload[] overloads) { // Make sure all overloads are distinct overloads = overloads.Distinct().ToArray(); // If there is only one overload: use a Sequence if (overloads.Length == 1) { return(new Sequence(overloads.Single().ToParameterList(allParameters))); } // If there is an empty overload: use an Option and recurse Overload emptyOverload = overloads.FirstOrDefault(overload => overload.All(flag => !flag)); if (emptyOverload != null) { return(new Option { Value = FromOverloads(allParameters, overloads.Except(new[] { emptyOverload }).ToArray()) }); } // Find contiguous areas of parameters that are independent from the rest. // Use a Sequence containing the constant parts and recurse for the independent areas. Interval[] independentAreas = GetIndependentAreas(new HashSet <Overload>(overloads)); if (independentAreas.Any()) { var sequence = new Sequence(); // Pad independent areas with zero-length dummy intervals var pairs = independentAreas.Prepend(new Interval()).Concat(new Interval()).Pairwise(); foreach (Tuple <Interval, Interval> pair in pairs) { if (pair.Item1.Length > 0) { sequence.Add(FromArea(allParameters, overloads, pair.Item1)); } for (int i = pair.Item1.End; i < pair.Item2.Start; i++) { sequence.Add(allParameters[i]); } } return(sequence); } // If there are no independent areas: // Find all partitions of the overloads and use the one that yields the shortest representation. // Ignore the trivial one-group partition as this will result in an endless recursion. IEnumerable <Overload[][]> overloadPartitions = Partitioning.GetAllPartitions(overloads) .Where(partition => partition.Length > 1); IEnumerable <Choice> possibleRepresentations = overloadPartitions .Select(overloadGroups => new Choice(overloadGroups.Select(overloadGroup => FromOverloads(allParameters, overloadGroup.ToArray())))); return(possibleRepresentations.MinBy(representation => representation.ParameterCount)); }
private BodyPartRecord GetBestBodyPartToEat(Pawn ingester, float nutritionWanted) { IEnumerable <BodyPartRecord> source = from x in InnerPawn.health.hediffSet.GetNotMissingParts() where x.depth == BodyPartDepth.Outside && FoodUtility.GetBodyPartNutrition(InnerPawn, x) > 0.001f select x; if (!source.Any()) { return(null); } return(source.MinBy((BodyPartRecord x) => Mathf.Abs(FoodUtility.GetBodyPartNutrition(InnerPawn, x) - nutritionWanted))); }
/// <summary> /// Generates either a Title-only or Title + Prefix Rank with the lowest tier possible. /// </summary> /// <param name="titles">The collection of titles to use.</param> /// <returns>The generated Rank object, or null if none could be generated.</returns> private Rank LowestRankFrom(IEnumerable <Word> titles) { if (!titles.Any()) { return(null); } var nextTitle = titles.MinBy(title => title.Tier); // We don't check positively tiered prefixes because a title on its own is always tiered lower. var negativePrefixes = UnusedPrefixesFor(nextTitle).Where(prefix => prefix.Tier < 0); return(!negativePrefixes.Any() ? new Rank(nextTitle) : new Rank(nextTitle, prefix: negativePrefixes.MinBy(prefix => prefix.Tier))); }
void RecalculateSoonestTimetableItemForDestination(Destination dest) { IEnumerable <TimetableItem> timetableToDestination = GameManager.instance.timetable.Where(t => t.destination == dest && t.platform != null); //collection of timetable items to this destination that have a platform assigned if (timetableToDestination.Any()) //if no timetable items to this destination skip { dest.SetSoonestTimetableItem(timetableToDestination.MinBy(t => t.scheduledDepartureTime)); //if there are, retrieve the earliest one } else { dest.SetSoonestTimetableItem(null); } }
public void Test_MinBy_NullComparerUsesDefault() { // Arrange. IEnumerable <TestContainer <int> > items = Enumerable.Range(1, 10).Select(i => new TestContainer <int> { Item = i }); // Act. TestContainer <int> min = items.MinBy(item => item.Item, null); // Assert. Assert.Equal(1, min.Item); }
private static float GetMinimumDistanceBetweenPositions( Vec3 position, IEnumerable <ICastleKeyPosition> referencePositions, out ICastleKeyPosition closestCastlePosition) { if (referencePositions != null && referencePositions.Count <ICastleKeyPosition>() != 0) { closestCastlePosition = referencePositions.MinBy <ICastleKeyPosition, float>((Func <ICastleKeyPosition, float>)(rp => rp.GetPosition().DistanceSquared(position))); return((float)Math.Sqrt((double)closestCastlePosition.GetPosition().DistanceSquared(position))); } closestCastlePosition = (ICastleKeyPosition)null; return(-1f); }
private void CalculateAffectedItems(FrameworkElement view) { if (((PatternPlacementView)view).IsSelected) { _affectedItems = SelectedItems.Cast <PatternPlacementViewModel>(); _minTick = _affectedItems.MinBy(pp => pp.Start); (_minTrack, _maxTrack) = _affectedItems.MinMaxBy(pp => pp.TrackIndex); } else { _affectedItems = new[] { (PatternPlacementViewModel)view.DataContext }; _minTick = _minTrack = _maxTrack = (PatternPlacementViewModel)view.DataContext; } }
private static LykkeArbitrageRow GetBestByProperty(IEnumerable <LykkeArbitrageRow> arbitrages, ArbitrageProperty property) { switch (property) { case ArbitrageProperty.Volume: return(arbitrages.MaxBy(x => x.VolumeInUsd)); case ArbitrageProperty.Spread: return(arbitrages.MinBy(x => x.Spread)); default: return(arbitrages.MaxBy(x => x.PnL)); } }
private IShipAttackable __SelectHighestPriorityAttackTgt(IEnumerable<IShipAttackable> availableAttackTgts) { return availableAttackTgts.MinBy(target => Vector3.SqrMagnitude(target.Position - Position)); }
//------------------------------------------------------------------ public Car FindClosestCar(IEnumerable <Car> cars) { return cars.MinBy (Distance); }