Context Menus & Progress Bars

We now have a context menu UI for in-game actions, right click on an item to activate
Database view has a progress bar (finally!)
Data structures for Megacorps and loadouts
Towing task complete? needs testing
This commit is contained in:
hyperion51 2020-05-10 00:16:33 +01:00
commit c24c155673
93 changed files with 1410 additions and 324 deletions

View file

@ -17,7 +17,7 @@ public abstract class AgentTask : DatabaseEntry
[JsonProperty("zone"), Key(2)]
public Guid Zone;
[JsonProperty("assignedEntity"), Key(3)]
[JsonProperty("reserved"), Key(3)]
public bool Reserved;
[IgnoreMember] public abstract TaskType Type { get; }

View file

@ -12,15 +12,19 @@ public class StationTowing : AgentTask
[IgnoreMember] public override TaskType Type => TaskType.Tow;
[JsonProperty("station"), Key(4)]
private Guid _station;
public Guid Station;
[JsonProperty("targetOrbit"), Key(5)]
private Guid _targetOrbit;
[JsonProperty("orbitParent"), Key(5)]
public Guid OrbitParent;
[JsonProperty("orbitDistance"), Key(6)]
public float OrbitDistance;
public StationTowing(Guid zone, Guid station, Guid targetOrbit)
public StationTowing(Guid zone, Guid station, Guid orbitParent, float orbitDistance)
{
Zone = zone;
_station = station;
_targetOrbit = targetOrbit;
Station = station;
OrbitParent = orbitParent;
OrbitDistance = orbitDistance;
}
}

View file

@ -8,7 +8,7 @@ using static Unity.Mathematics.math;
public class VelocityMatch : AgentBehavior
{
public event Action OnMatch;
public Guid TargetOrbit;
public float2 TargetVelocity;
private Thruster _thrust;
private Turning _turning;
private const float TargetThreshold = .1f;
@ -21,12 +21,17 @@ public class VelocityMatch : AgentBehavior
_thrust = Entity.Axes.Keys.FirstOrDefault(x => x is Thruster) as Thruster;
_turning = Entity.Axes.Keys.FirstOrDefault(x => x is Turning) as Turning;
}
public void Clear()
{
OnMatch = null;
}
public override void Update(float delta)
{
if (TargetOrbit != Guid.Empty && _thrust != null && _turning != null)
if (_thrust != null && _turning != null)
{
var deltaV = _context.GetOrbitVelocity(TargetOrbit) - Entity.Velocity;
var deltaV = TargetVelocity - Entity.Velocity;
if(length(deltaV) < TargetThreshold)
OnMatch?.Invoke();
Entity.Axes[_turning] = TurningInput(deltaV);
@ -39,7 +44,7 @@ public class VelocityMatch : AgentBehavior
get
{
var velocity = length(Entity.Velocity);
var deltaV = _context.GetOrbitVelocity(TargetOrbit) - Entity.Velocity;
var deltaV = TargetVelocity - Entity.Velocity;
var stoppingTime = length(deltaV) / (_thrust.Thrust / Entity.Mass);
var stoppingDistance = stoppingTime * (velocity / 2);

View file

@ -53,6 +53,9 @@ public class InspectableTextAttribute : InspectableFieldAttribute { }
[AttributeUsage(AttributeTargets.Field)]
public class InspectablePrefabAttribute : InspectableFieldAttribute { }
[AttributeUsage(AttributeTargets.Field)]
public class InspectableTextureAttribute : InspectableFieldAttribute { }
[AttributeUsage(AttributeTargets.Field)]
public class TemperatureInspectableAttribute : InspectableFieldAttribute { }

View file

@ -36,8 +36,9 @@ public interface IPersistentBehavior//<T> where T : IBehavior
public interface IController
{
bool Available { get; }
TaskType JobType { get; }
void AssignTask(Guid task);
TaskType TaskType { get; }
Guid Zone { get; }
void AssignTask(Guid task, List<SimplifiedZoneData> path);
}
[MessagePackObject,

View file

@ -1,4 +1,5 @@
using System.Collections;
using System;
using System.Collections;
using System.Collections.Generic;
using MessagePack;
using Newtonsoft.Json;
@ -19,7 +20,25 @@ public abstract class ControllerData : BehaviorData
public float TangentSensitivity = 4;
}
// public abstract class Controller
// public abstract class Controller : IController
// {
// public abstract bool Available { get; }
// public abstract TaskType TaskType { get; }
// public Guid Zone { get; }
//
// private GameContext _context;
// private Entity _entity;
// private Guid _task;
// private List<SimplifiedZoneData> _path;
//
// public Controller(GameContext context, Entity entity)
// {
//
// }
//
// public void AssignTask(Guid task, List<SimplifiedZoneData> path)
// {
// _task = task;
// _path = path;
// }
// }

View file

@ -20,8 +20,9 @@ public class PatrolControllerData : ControllerData
public class PatrolController : IBehavior, IController
{
public TaskType JobType => TaskType.Tow;
public TaskType TaskType => TaskType.Tow;
public bool Available => false;
public Guid Zone => _entity.Zone;
public BehaviorData Data => _data;
private PatrolControllerData _data;
@ -55,7 +56,7 @@ public class PatrolController : IBehavior, IController
RandomTarget();
}
public void AssignTask(Guid task)
public void AssignTask(Guid task, List<SimplifiedZoneData> path)
{
throw new NotImplementedException();
}

View file

@ -1,8 +1,11 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[MessagePackObject, JsonObject(MemberSerialization.OptIn), EntityTypeRestriction(HullType.Ship)]
public class TowingControllerData : ControllerData
@ -15,8 +18,9 @@ public class TowingControllerData : ControllerData
public class TowingController : IBehavior, IPersistentBehavior, IController
{
public TaskType JobType => TaskType.Tow;
public TaskType TaskType => TaskType.Tow;
public bool Available => _towingTask != Guid.Empty;
public Guid Zone => _entity.Zone;
public BehaviorData Data => _data;
private TowingControllerData _data;
@ -24,6 +28,11 @@ public class TowingController : IBehavior, IPersistentBehavior, IController
private Entity _entity;
private Gear _item;
private Guid _towingTask;
private List<SimplifiedZoneData> _path;
private TowingPhase _towingPhase = TowingPhase.Pickup;
private MovementPhase _movementPhase = MovementPhase.Locomotion;
private Locomotion _locomotion;
private VelocityMatch _velocityMatch;
public TowingController(GameContext context, TowingControllerData data, Entity entity, Gear item)
{
@ -35,11 +44,81 @@ public class TowingController : IBehavior, IPersistentBehavior, IController
public void Initialize()
{
_locomotion = new Locomotion(_context, _entity, _data);
_velocityMatch = new VelocityMatch(_context, _entity, _data);
}
public void Update(float delta)
{
if (_path.Any())
{
_locomotion.Update(delta);
if (length(_entity.Position - _locomotion.Objective) < _context.GlobalData.WarpDistance)
{
_context.Warp(_entity, _path[0].ZoneID);
_path.RemoveAt(0);
if(_path.Any())
SetWormholeDestination();
}
}
else
{
var towingTask = _context.Cache.Get<StationTowing>(_towingTask);
var destination = float2(0);
var velocity = float2(0);
if (_towingPhase == TowingPhase.Pickup)
{
destination = _context.ZoneEntities[_entity.Zone][towingTask.Station].Position;
velocity = _context.ZoneEntities[_entity.Zone][towingTask.Station].Velocity;
}
else
{
var orbitParent = _context.GetOrbitPosition(towingTask.OrbitParent);
var parentToUs = _entity.Position - orbitParent;
var nearestPointInOrbit = orbitParent + normalize(parentToUs) * towingTask.OrbitDistance;
destination = nearestPointInOrbit;
velocity = _context.GetOrbitVelocity(towingTask.OrbitParent);
}
_velocityMatch.TargetVelocity = velocity;
if (_movementPhase == MovementPhase.Locomotion)
{
var matchDistanceTime = _velocityMatch.MatchDistanceTime;
_locomotion.Objective = destination + velocity * matchDistanceTime.y;
_locomotion.Update(delta);
var distance = length(destination - _entity.Position);
if (distance < matchDistanceTime.x)
{
_movementPhase = MovementPhase.Slowdown;
_velocityMatch.Clear();
if (_towingPhase == TowingPhase.Pickup)
_velocityMatch.OnMatch += () =>
{
var target = _context.ZoneEntities[_entity.Zone][towingTask.Station];
_entity.Children.Add(towingTask.Station);
target.Parent = _entity.ID;
_towingPhase = TowingPhase.Delivery;
_movementPhase = MovementPhase.Locomotion;
};
else
_velocityMatch.OnMatch += () =>
{
var orbit = _context.CreateOrbit(towingTask.OrbitParent, _entity.Position);
var target = _context.ZoneEntities[_entity.Zone][towingTask.Station] as OrbitalEntity;
_entity.Children.Remove(towingTask.Station);
target.Parent = Guid.Empty;
target.OrbitData = orbit.ID;
};
}
}
else
{
_velocityMatch.Update(delta);
}
}
}
public PersistentBehaviorData Store()
@ -56,9 +135,18 @@ public class TowingController : IBehavior, IPersistentBehavior, IController
_towingTask = towingControllerPersistence.TowingTask;
}
public void AssignTask(Guid task)
public void AssignTask(Guid task, List<SimplifiedZoneData> path)
{
_towingTask = task;
_path = path;
_path.RemoveAt(0);
if(_path.Any())
SetWormholeDestination();
}
private void SetWormholeDestination()
{
_locomotion.Objective = _context.WormholePosition(_entity.Zone, _path[0].ZoneID);
}
}
@ -67,3 +155,15 @@ public class TowingControllerPersistence : PersistentBehaviorData
[JsonProperty("towingTask"), Key(0)]
public Guid TowingTask;
}
public enum TowingPhase
{
Pickup,
Delivery
}
public enum MovementPhase
{
Locomotion,
Slowdown
}

View file

@ -31,13 +31,13 @@ public interface INamedEntry
Union(10, typeof(ZoneData)),
Union(11, typeof(Player)),
Union(12, typeof(Corporation)),
Union(13, typeof(ShipData)),
Union(13, typeof(MegaCorporation)),
Union(14, typeof(StationData)),
Union(15, typeof(OrbitData)),
Union(16, typeof(PlanetData)),
Union(17, typeof(PersonalityAttribute)),
Union(18, typeof(AgentTask)),
// Union(17, typeof(ShipData)),
Union(19, typeof(LoadoutData)),
JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(JsonKnownTypesConverter<DatabaseEntry>))]
//[Union(21, typeof(ContractData))]
//[Union(22, typeof(Station))]
@ -81,8 +81,43 @@ public class Corporation : DatabaseEntry, INamedEntry
}
}
[RethinkTable("Galaxy"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class ShipData : DatabaseEntry
[RethinkTable("Galaxy"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class MegaCorporation : DatabaseEntry, INamedEntry
{
[InspectableField, JsonProperty("name"), Key(1)]
public string Name;
[InspectableTexture, JsonProperty("logo"), Key(2)]
public string Logo;
[InspectableDatabaseLink(typeof(PersonalityAttribute)), JsonProperty("initialFleet"), Key(3)]
public Dictionary<Guid, float> Personality = new Dictionary<Guid, float>();
[InspectableDatabaseLink(typeof(LoadoutData)), JsonProperty("initialFleet"), Key(4)]
public Dictionary<Guid, int> InitialFleet = new Dictionary<Guid, int>();
[IgnoreMember] public string EntryName
{
get => Name;
set => Name = value;
}
}
[RethinkTable("Items"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class LoadoutData : DatabaseEntry, INamedEntry
{
[InspectableField, JsonProperty("name"), Key(1)]
public string Name;
[InspectableDatabaseLink(typeof(HullData)), JsonProperty("hull"), Key(2)]
public Guid Hull;
[JsonProperty("items"), Key(3)]
public List<Guid> Items = new List<Guid>();
[IgnoreMember] public string EntryName
{
get => Name;
set => Name = value;
}
}

View file

@ -6,6 +6,7 @@ using Unity.Mathematics;
using static Unity.Mathematics.math;
using float2 = Unity.Mathematics.float2;
using Random = Unity.Mathematics.Random;
using JM.LinqFaster;
public class GameContext
{
@ -14,6 +15,7 @@ public class GameContext
public Dictionary<Guid, Dictionary<Guid, Entity>> ZoneEntities = new Dictionary<Guid, Dictionary<Guid, Entity>>();
public Dictionary<string, GalaxyMapLayerData> MapLayers = new Dictionary<string, GalaxyMapLayerData>();
public Dictionary<Guid, List<IController>> CorporationControllers = new Dictionary<Guid, List<IController>>();
public Dictionary<Guid, SimplifiedZoneData> GalaxyZones;
private Action<string> _logger;
@ -23,14 +25,29 @@ public class GameContext
private double _time;
private float _deltaTime;
private GlobalData _globalData;
private HashSet<Guid> _loadedZones = new HashSet<Guid>();
private HashSet<Guid> _orbits = new HashSet<Guid>();
private Dictionary<Guid, float2> _orbitVelocities = new Dictionary<Guid, float2>();
private Dictionary<Guid, float2> _orbitPositions = new Dictionary<Guid, float2>();
private Dictionary<Guid, float2> _previousOrbitPositions = new Dictionary<Guid, float2>();
private Guid _forceLoadZone;
public GlobalData GlobalData => _globalData ?? (_globalData = Cache.GetAll<GlobalData>().FirstOrDefault());
public DatabaseCache Cache { get; }
public Guid ForceLoadZone
{
get => _forceLoadZone;
set
{
if(_forceLoadZone != Guid.Empty && ZoneEntities[_forceLoadZone].Count == 0)
UnloadZone(_forceLoadZone);
_forceLoadZone = value;
if(!_loadedZones.Contains(_forceLoadZone))
LoadZone(_forceLoadZone);
}
}
public double Time
{
get => _time;
@ -68,24 +85,6 @@ public class GameContext
_logger(s);
}
public IEnumerable<Entity> GetEntities(Guid zone)
{
return ZoneEntities[zone].Values;
}
public void InitializeZone(Guid zoneID)
{
var zoneData = Cache.Get<ZoneData>(zoneID);
foreach (var orbit in zoneData.Orbits) _orbits.Add(orbit);
// TODO: Associate planets with stored entities for planetary colonies
ZonePlanets[zoneID] = zoneData.Planets;
// TODO: Load stored entities
ZoneEntities[zoneID] = new Dictionary<Guid, Entity>();
}
public void Update()
{
_previousOrbitPositions = _orbitPositions;
@ -101,22 +100,33 @@ public class GameContext
foreach (var corporation in Cache.GetAll<Corporation>())
{
foreach (var taskController in corporation.Tasks
foreach (var tasks in corporation.Tasks
.Select(id => Cache.Get<AgentTask>(id)) // Fetch the tasks from the database cache
.Where(task => task.Reserved == false) // Filter out tasks that have already been reserved
.GroupBy(task => task.Type) // Group tasks by job type
.Where(grouping =>
CorporationControllers[corporation.ID] // Filter out groupings with no available controller
.Any(controller => controller.Available && controller.JobType == grouping.Key))
.Select(grouping => grouping // Pair each task in remaining groupings with available controllers
.OrderByDescending(task => task.Priority) // Sort by priority, highest first
.Zip(CorporationControllers[corporation.ID]
.Where(controller => controller.Available && controller.JobType == grouping.Key),
(task, controller) => new {task, controller}))
.SelectMany(x => x)) // Flatten groupings
.Where(task => !task.Reserved) // Filter out tasks that have already been reserved
.GroupBy(task => task.Type)) // Group tasks by type
{
taskController.task.Reserved = true;
taskController.controller.AssignTask(taskController.task.ID);
// Create a list of available controllers for this task type
var availableControllers = CorporationControllers[corporation.ID]
.Where(controller => controller.TaskType == tasks.Key && controller.Available).ToList();
// Iterate over the highest priority tasks for which controllers are available
foreach (var task in tasks.OrderByDescending(task => task.Priority).Take(availableControllers.Count))
{
// Find the nearest controller for this task
IController nearestController = availableControllers[0];
List<SimplifiedZoneData> nearestControllerPath = FindPath(GalaxyZones[availableControllers.First().Zone], GalaxyZones[task.Zone], true);
foreach (var controller in availableControllers.Skip(1))
{
var path = FindPath(GalaxyZones[controller.Zone], GalaxyZones[task.Zone], true);
if (path.Count < nearestControllerPath.Count)
{
nearestControllerPath = path;
nearestController = controller;
}
}
task.Reserved = true;
nearestController.AssignTask(task.ID, nearestControllerPath);
}
}
}
@ -127,11 +137,57 @@ public class GameContext
}
}
public IEnumerable<Entity> GetEntities(Guid zone)
{
return ZoneEntities[zone].Values;
}
public void LoadZone(Guid zone)
{
var zoneData = Cache.Get<ZoneData>(zone);
_loadedZones.Add(zone);
foreach (var orbit in zoneData.Orbits) _orbits.Add(orbit);
// TODO: Associate planets with stored entities for planetary colonies
ZonePlanets[zone] = zoneData.Planets;
// TODO: Load stored entities
ZoneEntities[zone] = new Dictionary<Guid, Entity>();
}
public void UnloadZone(Guid zone)
{
var zoneData = Cache.Get<ZoneData>(zone);
foreach (var orbit in zoneData.Orbits) _orbits.Remove(orbit);
_loadedZones.Remove(zone);
ZoneEntities.Remove(zone);
ZonePlanets.Remove(zone);
foreach (var orbit in zoneData.Orbits) _orbits.Remove(orbit);
}
public void Warp(Entity entity, Guid targetZone)
{
if (length(entity.Position - WormholePosition(entity.Zone, targetZone)) < GlobalData.WarpDistance)
{
var sourceZone = entity.Zone;
// Remove entity from source zone
ZoneEntities[sourceZone].Remove(entity.ID);
// Unload source zone if empty and unobserved
if(ForceLoadZone != sourceZone && ZoneEntities[sourceZone].Count == 0)
UnloadZone(sourceZone);
// Load target zone if not yet loaded
if(!_loadedZones.Contains(targetZone))
LoadZone(targetZone);
entity.Zone = targetZone;
entity.Position = WormholePosition(targetZone, sourceZone);
ZoneEntities[targetZone][entity.ID] = entity;
}
}
// Determine orbital position recursively, caching parent positions to avoid repeated calculations
@ -145,7 +201,7 @@ public class GameContext
{
var orbitData = Cache.Get<OrbitData>(orbit);
_orbitPositions[orbit] = GetOrbitPosition(orbitData.Parent) + (orbitData.Period < .01f ? float2.zero :
OrbitData.Evaluate((float) (Time / -orbitData.Period * GlobalData.OrbitSpeedMultiplier + orbitData.Phase)) *
OrbitData.Evaluate((float) frac(Time / -orbitData.Period * GlobalData.OrbitSpeedMultiplier + orbitData.Phase)) *
orbitData.Distance);
}
@ -162,6 +218,35 @@ public class GameContext
{
return _orbitVelocities.ContainsKey(orbit) ? _orbitVelocities[orbit] : float2.zero;
}
public OrbitData CreateOrbit(Guid parent, float2 position)
{
var parentOrbit = Cache.Get<OrbitData>(parent);
var parentPosition = GetOrbitPosition(parent);
var delta = position - parentPosition;
var distance = length(delta);
var period = OrbitalPeriod(distance);
var phase = atan2(delta.y, delta.x) / (PI * 2);
var storedPhase = (float) frac(Time / -period * GlobalData.OrbitSpeedMultiplier - phase);
var orbit = new OrbitData
{
Context = this,
Distance = distance,
ID = Guid.NewGuid(),
Parent = parent,
Period = period,
Phase = storedPhase,
Zone = parentOrbit.Zone
};
Cache.Add(orbit);
return orbit;
}
public float OrbitalPeriod(float distance)
{
return pow(distance, GlobalData.OrbitPeriodExponent) * GlobalData.OrbitPeriodMultiplier;
}
// public int ItemTier(CraftedItemData itemData)
// {
@ -389,4 +474,37 @@ public class GameContext
Cache.Add(newCommodity);
return newCommodity;
}
class DijkstraNode
{
public float Cost;
public DijkstraNode Parent;
public SimplifiedZoneData Zone;
}
public List<SimplifiedZoneData> FindPath(SimplifiedZoneData source, SimplifiedZoneData target, bool bestFirst = false)
{
SortedList<float,DijkstraNode> members = new SortedList<float,DijkstraNode>{{0,new DijkstraNode{Zone = source}}};
List<DijkstraNode> searched = new List<DijkstraNode>();
while (true)
{
var s = members.FirstOrDefault(m => !searched.Contains(m.Value)).Value; // Lowest cost unsearched node
if (s == null) return null; // No vertices left unsearched
if (s.Zone == target) // We found the path
{
Stack<DijkstraNode> path = new Stack<DijkstraNode>(); // Since we start at the end, use a LIFO collection
path.Push(s);
while(path.Peek().Parent!=null) // Keep pushing until we reach the start, which has no parent
path.Push(path.Peek().Parent);
return path.Select(dv => dv.Zone).ToList();
}
// For each adjacent star (filter already visited zones unless heuristic is in use)
foreach (var dijkstraStar in s.Zone.Links.WhereSelectF(i => !bestFirst || members.All(m => m.Value.Zone != GalaxyZones[i]),
// Cost is parent cost plus distance
i => new DijkstraNode {Parent = s, Zone = GalaxyZones[i], Cost = s.Cost + length(s.Zone.Position - GalaxyZones[i].Position)}))
// Add new member to list, sorted by cost plus optional heuristic
members.Add(bestFirst ? dijkstraStar.Cost + length(dijkstraStar.Zone.Position - target.Position) : dijkstraStar.Cost, dijkstraStar);
searched.Add(s);
}
}
}

View file

@ -94,13 +94,13 @@ public class GalaxyRequestMessage : Message
[MessagePackObject]
public class GalaxyResponseMessage : Message
{
[Key(0)] public GalaxyResponseZone[] Zones;
[Key(0)] public SimplifiedZoneData[] Zones;
[Key(1)] public GalaxyMapLayerData StarDensity;
[Key(2)] public GlobalData GlobalData;
}
[MessagePackObject]
public class GalaxyResponseZone
public class SimplifiedZoneData
{
[Key(0)] public Guid ZoneID;
[Key(1)] public Guid[] Links;

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8a827381b8571114091cd0fc9c0ebd1f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,207 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
/// <summary>
/// Provides faster array and list specific extension methods with
/// the same semantics as the Linq extensions methods.
/// </summary>
public static partial class LinqFaster
{
// ------------------------------ Arrays --------------------------
/// <summary>
/// Applies an accumulator function over an array.
/// </summary>
/// <param name="source">An array to aggregate over.</param>
/// <param name="func">An accumulator function to be invoked on each element</param>
/// <returns>The final accumulator value</returns>
public static TSource AggregateF<TSource>(this TSource[] source, Func<TSource, TSource, TSource> func)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (func == null)
{
throw Error.ArgumentNull("func");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
TSource result = source[0];
for (int i = 1; i < source.Length; i++)
{
result = func(result, source[i]);
}
return result;
}
/// <summary>
/// Applies an accumulator function over an array. The specified seed
/// value is used as the initial accumulator value.
/// </summary>
/// <param name="source">An array to aggregate over.</param>
/// <param name="seed">The initial accumulator value.</param>
/// <param name="func">An accumulator function to be invoked on each element</param>
/// <returns>The final accumulator value</returns>
public static TAccumulate AggregateF<TSource, TAccumulate>(this TSource[] source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (func == null)
{
throw Error.ArgumentNull("func");
}
TAccumulate result = seed;
foreach (var v in source)
{
result = func(result, v);
}
return result;
}
/// <summary>
/// Applies an accumulator function over an array. The specified seed
/// value is used as the initial accumulator value, and the specified
/// function is used to select the result value.
/// </summary>
/// <param name="source">An array to aggregate over.</param>
/// <param name="seed">The initial accumulator value.</param>
/// <param name="func">An accumulator function to be invoked on each element</param>
/// <param name="resultSelector">A function to transform the final accumulator value into the result value.</param>
/// <returns>The transformed final accumulator value</returns>
public static TResult AggregateF<TSource, TAccumulate, TResult>(this TSource[] source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (func == null)
{
throw Error.ArgumentNull("func");
}
if (resultSelector == null)
{
throw Error.ArgumentNull("resultSelector");
}
TAccumulate result = seed;
foreach (var v in source)
{
result = func(result, v);
}
return resultSelector(result);
}
// ------------------------------ Lists --------------------------
/// <summary>
/// Applies an accumulator function over a List.
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source">A List to aggregate over.</param>
/// <param name="func">An accumulator function to be invoked on each element</param>
/// <returns>The final accumulator value</returns>
public static TSource AggregateF<TSource>(this List<TSource> source, Func<TSource, TSource, TSource> func)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (func == null)
{
throw Error.ArgumentNull("func");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
TSource result = source[0];
for (int i = 1; i < source.Count; i++)
{
result = func(result, source[i]);
}
return result;
}
/// <summary>
/// Applies an accumulator function over a List. The specified seed
/// value is used as the initial accumulator value.
/// </summary>
/// <param name="source">A List to aggregate over.</param>
/// <param name="seed">The initial accumulator value.</param>
/// <param name="func">An accumulator function to be invoked on each element</param>
/// <returns>The final accumulator value</returns>
public static TAccumulate AggregateF<TSource, TAccumulate>(this List<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (func == null)
{
throw Error.ArgumentNull("func");
}
TAccumulate result = seed;
for (int i = 0; i < source.Count; i++)
{
result = func(result, source[i]);
}
return result;
}
/// <summary>
/// Applies an accumulator function over a List. The specified seed
/// value is used as the initial accumulator value, and the specified
/// function is used to select the result value.
/// </summary>
/// <param name="source">A List to aggregate over.</param>
/// <param name="seed">The initial accumulator value.</param>
/// <param name="func">An accumulator function to be invoked on each element</param>
/// <param name="resultSelector">A function to transform the final accumulator value into the result value.</param>
/// <returns>The transformed final accumulator value</returns>
public static TResult AggregateF<TSource, TAccumulate, TResult>(this List<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (func == null)
{
throw Error.ArgumentNull("func");
}
if (resultSelector == null)
{
throw Error.ArgumentNull("resultSelector");
}
TAccumulate result = seed;
for (int i = 0; i < source.Count; i++)
{
result = func(result, source[i]);
}
return resultSelector(result);
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: c982561dda0276f48b28c8fa12295ad4
timeCreated: 1518622478
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- ARRAYS --------------------------------------------
/// <summary>
/// Determines whether an array contains any elements
/// </summary>
/// <param name="source">The array to check for emptiness</param>
/// <returns>true if the source array contains any elements, otherwise, false/</returns>
public static bool AnyF<T>(this T[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
return source.Length > 0;
}
/// <summary>
/// Determines whether any element of an array satifies a condition.
/// </summary>
/// <param name="source">An array whose elements to apply the predicate to.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>true if any elements in the source array pass the test in the specified predicate; otherwise, false.</returns>
public static bool AnyF<TSource>(this TSource[] source, Predicate<TSource> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
return Array.Exists(source, predicate);
}
/// <summary>
/// Determines whether all elements of an array satisfy a condition.
/// </summary>
/// <param name="source">An array that contains the elements to apply the predicate to.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>true if every element of the source array passes the test in the specified
/// predicate, or if the array is empty; otherwise, false</returns>
public static bool AllF<TSource>(this TSource[] source, Predicate<TSource> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
return Array.TrueForAll(source, predicate);
}
// -------------------------- Lists --------------------------------------------
/// <summary>
/// Determines whether a list contains any elements
/// </summary>
/// <param name="source">The list to check for emptiness</param>
/// <returns>true if the source list contains any elements, otherwise, false/</returns>
public static bool AnyF<T>(this List<T> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
return source.Count > 0;
}
/// <summary>
/// Determines whether any element of an array satifies a condition.
/// </summary>
/// <param name="source">An array whose elements to apply the predicate to.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>true if any elements in the source array pass the test in the specified predicate; otherwise, false.</returns>
public static bool AnyF<TSource>(this List<TSource> source, Predicate<TSource> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
return source.Exists(predicate);
}
/// <summary>
/// Determines whether all elements of a list satisfy a condition.
/// </summary>
/// <param name="source">A list that contains the elements to apply the predicate to.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>true if every element of the source array passes the test in the specified
/// predicate, or if the list is empty; otherwise, false</returns>
public static bool AllF<TSource>(this List<TSource> source, Predicate<TSource> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
return source.TrueForAll(predicate);
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 0f33f6b80d5e4d24bb1f5b42a26585e8
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,633 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- ARRAYS --------------------------------------------
/// <summary>
/// Computes the average of an array
/// </summary>
/// <param name="source">The array to calculate the average of.</param>
/// <returns>The average of the array.</returns>
public static double AverageF(this int[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
long sum = 0;
checked
{
for (int i = 0; i < source.Length; i++)
{
sum += source[i];
}
}
return (double)sum / source.Length;
}
/// <summary>
/// Computes the average of values obtained by invoking a transform function on
/// each element of the input array.
/// </summary>
/// <param name="source">The array to calculate the transformed average of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The average of the array.</returns>
public static double AverageF<T>(this T[] source, Func<T, int> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
long sum = 0;
checked
{
for (int i = 0; i < source.Length; i++)
{
sum += selector(source[i]);
}
}
return (double)sum / source.Length;
}
/// <summary>
/// Computes the average of an array
/// </summary>
/// <param name="source">The array to calculate the average of.</param>
/// <returns>The average of the array.</returns>
public static double AverageF(this long[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
long sum = 0;
checked
{
for (int i = 0; i < source.Length; i++)
{
sum += source[i];
}
}
return (double)sum / source.Length;
}
/// <summary>
/// Computes the average of values obtained by invoking a transform function on
/// each element of the input array.
/// </summary>
/// <param name="source">The array to calculate the transformed average of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The average of the array.</returns>
public static double AverageF<T>(this T[] source, Func<T, long> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
long sum = 0;
checked
{
for (int i = 0; i < source.Length; i++)
{
sum += selector(source[i]);
}
}
return (double)sum / source.Length;
}
/// <summary>
/// Computes the average of an array
/// </summary>
/// <param name="source">The array to calculate the average of.</param>
/// <returns>The average of the array.</returns>
public static float AverageF(this float[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
double sum = 0;
for (int i = 0; i < source.Length; i++)
{
sum += source[i];
}
return (float)(sum / source.Length);
}
/// <summary>
/// Computes the average of values obtained by invoking a transform function on
/// each element of the input array.
/// </summary>
/// <param name="source">The array to calculate the transformed average of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The average of the array.</returns>
public static float AverageF<T>(this T[] source, Func<T, float> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double sum = 0;
for (int i = 0; i < source.Length; i++)
{
sum += selector(source[i]);
}
return (float)(sum / source.Length);
}
/// <summary>
/// Computes the average of an array
/// </summary>
/// <param name="source">The array to calculate the average of.</param>
/// <returns>The average of the array.</returns>
public static double AverageF(this double[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
double sum = 0;
for (int i = 0; i < source.Length; i++)
{
sum += source[i];
}
return sum / source.Length;
}
/// <summary>
/// Computes the average of values obtained by invoking a transform function on
/// each element of the input array.
/// </summary>
/// <param name="source">The array to calculate the transformed average of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The average of the array.</returns>
public static double AverageF<T>(this T[] source, Func<T, double> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double sum = 0;
for (int i = 0; i < source.Length; i++)
{
sum += selector(source[i]);
}
return sum / source.Length;
}
/// <summary>
/// Computes the average of an array
/// </summary>
/// <param name="source">The array to calculate the average of.</param>
/// <returns>The average of the array.</returns>
public static decimal AverageF(this decimal[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
decimal sum = 0;
for (int i = 0; i < source.Length; i++)
{
sum += source[i];
}
return sum / source.Length;
}
/// <summary>
/// Computes the average of values obtained by invoking a transform function on
/// each element of the input array.
/// </summary>
/// <param name="source">The array to calculate the transformed average of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The average of the array.</returns>
public static decimal AverageF<T>(this T[] source, Func<T, decimal> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
decimal sum = 0;
for (int i = 0; i < source.Length; i++)
{
sum += selector(source[i]);
}
return sum / source.Length;
}
// -------------------------- Lists --------------------------------------------
/// <summary>
/// Computes the average of a list.
/// </summary>
/// <param name="source">The list to calculate the average of.</param>
/// <returns>The average of the list.</returns>
public static double AverageF(this List<int> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
long sum = 0;
checked
{
for (int i = 0; i < source.Count; i++)
{
sum += source[i];
}
}
return (double)sum / source.Count;
}
/// <summary>
/// Computes the average of values obtained by invoking a transform function on
/// each element of the input array.
/// </summary>
/// <param name="source">The array to calculate the transformed average of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The average of the array.</returns>
public static double AverageF<T>(this List<T> source, Func<T, int> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
long sum = 0;
checked
{
for (int i = 0; i < source.Count; i++)
{
sum += selector(source[i]);
}
}
return (double)sum / source.Count;
}
/// <summary>
/// Computes the average of a list.
/// </summary>
/// <param name="source">The list to calculate the average of.</param>
/// <returns>The average of the list.</returns>
public static double AverageF(this List<long> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
long sum = 0;
checked
{
for (int i = 0; i < source.Count; i++)
{
sum += source[i];
}
}
return (double)sum / source.Count;
}
/// <summary>
/// Computes the average of values obtained by invoking a transform function on
/// each element of the input array.
/// </summary>
/// <param name="source">The array to calculate the transformed average of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The average of the array.</returns>
public static double AverageF<T>(this List<T> source, Func<T, long> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
long sum = 0;
checked
{
for (int i = 0; i < source.Count; i++)
{
sum += selector(source[i]);
}
}
return (double)sum / source.Count;
}
/// <summary>
/// Computes the average of a list.
/// </summary>
/// <param name="source">The list to calculate the average of.</param>
/// <returns>The average of the list.</returns>
public static float AverageF(this List<float> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
double sum = 0;
for (int i = 0; i < source.Count; i++)
{
sum += source[i];
}
return (float)(sum / source.Count);
}
/// <summary>
/// Computes the average of values obtained by invoking a transform function on
/// each element of the input array.
/// </summary>
/// <param name="source">The array to calculate the transformed average of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The average of the array.</returns>
public static float AverageF<T>(this List<T> source, Func<T, float> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double sum = 0;
for (int i = 0; i < source.Count; i++)
{
sum += selector(source[i]);
}
return (float)(sum / source.Count);
}
/// <summary>
/// Computes the average of a list.
/// </summary>
/// <param name="source">The list to calculate the average of.</param>
/// <returns>The average of the list.</returns>
public static double AverageF(this List<double> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
double sum = 0;
for (int i = 0; i < source.Count; i++)
{
sum += source[i];
}
return sum / source.Count;
}
/// <summary>
/// Computes the average of values obtained by invoking a transform function on
/// each element of the input array.
/// </summary>
/// <param name="source">The array to calculate the transformed average of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The average of the array.</returns>
public static double AverageF<T>(this List<T> source, Func<T, double> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double sum = 0;
for (int i = 0; i < source.Count; i++)
{
sum += selector(source[i]);
}
return sum / source.Count;
}
/// <summary>
/// Computes the average of a list.
/// </summary>
/// <param name="source">The list to calculate the average of.</param>
/// <returns>The average of the list.</returns>
public static decimal AverageF(this List<decimal> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
decimal sum = 0;
for (int i = 0; i < source.Count; i++)
{
sum += source[i];
}
return sum / source.Count;
}
/// <summary>
/// Computes the average of values obtained by invoking a transform function on
/// each element of the input array.
/// </summary>
/// <param name="source">The array to calculate the transformed average of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The average of the array.</returns>
public static decimal AverageF<T>(this List<T> source, Func<T, decimal> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
decimal sum = 0;
for (int i = 0; i < source.Count; i++)
{
sum += selector(source[i]);
}
return sum / source.Count;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 03ad52f1464dca347a72680cef2af96a
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- ARRAYS --------------------------------------------
/// <summary>
/// Determines whether an array contains a specified element by using the
/// provided IEqualityComparer.
/// </summary>
/// <param name="source">An array in which to locate a value.</param>
/// <param name="value">The value to locate.</param>
/// <param name="comparer">An equality comparer to compare values.</param>
/// <returns>true if the source sequence contains an element that has the specified value; otherwise, false.</returns>
public static bool ContainsF<TSource>(this TSource[] source, TSource value, IEqualityComparer<TSource> comparer = null)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (comparer == null)
{
return Array.IndexOf(source, value) != -1;
}
foreach (TSource e in source)
{
if (comparer.Equals(e, value))
{
return true;
}
}
return false;
}
// -------------------------- Lists --------------------------------------------
/// <summary>
/// Determines whether a list contains a specified element by using the
/// provided IEqualityComparer.
/// </summary>
/// <param name="source">A list in which to locate a value.</param>
/// <param name="value">The value to locate.</param>
/// <param name="comparer">An equality comparer to compare values.</param>
/// <returns>true if the source sequence contains an element that has the specified value; otherwise, false.</returns>
public static bool ContainsF<TSource>(this List<TSource> source, TSource value, IEqualityComparer<TSource> comparer = null)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (comparer == null)
{
return source.IndexOf(value) != -1;
}
for (int i = 0; i < source.Count; i++)
{
if (comparer.Equals(source[i], value))
{
return true;
}
}
return false;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: b2bd3dc5ff6476641a57d43d3692ce23
timeCreated: 1518622477
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,86 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- Arrays --------------------------------------------
/// <summary>
/// Returns a number that represents how many elements in the specified
/// array satisfy a condition.
/// </summary>
/// <param name="source">An array that contains elements to be tested and counted.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>A number that represents how many elements in the array satisfy the condition
/// in the predicate function.</returns>
public static int CountF<T>(this T[] source, Func<T, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
int count = 0;
for (int i = 0; i < source.Length; i++)
{
checked
{
if (predicate(source[i]))
{
count++;
}
}
}
return count;
}
// ------------------------------ Lists ---------------------
/// <summary>
/// Returns a number that represents how many elements in the specified
/// list satisfy a condition.
/// </summary>
/// <param name="source">A list that contains elements to be tested and counted.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>A number that represents how many elements in the list satisfy the condition
/// in the predicate function.</returns>
public static int CountF<T>(this List<T> source, Func<T, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
int count = 0;
for (int i = 0; i < source.Count; i++)
{
checked
{
if (predicate(source[i]))
{
count++;
}
}
}
return count;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 5337c0db0f170274587167b132a927c7
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,53 @@
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- LISTS --------------------------------------------
/// <summary>
/// Removes duplicate elements from source, does not maintain order. Elements will be
/// sorted in ascending order.
/// </summary>
/// <param name="source">The list to remove duplicate elements from.</param>
/// <param name="eqComparer">Optional IEqualityComparer to compare values.</param>
/// <param name="comparer">Optional IComparer to compare values.</param>
public static void DistinctInPlaceF<TSource>(this List<TSource> source, IEqualityComparer<TSource> eqComparer = null, IComparer<TSource> comparer = null)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (comparer == null)
{
comparer = Comparer<TSource>.Default;
}
if (eqComparer == null)
{
eqComparer = EqualityComparer<TSource>.Default;
}
source.Sort(comparer);
TSource oldV = source[0];
int pos = 1;
for (int i = 1; i < source.Count; i++)
{
var newV = source[i];
source[pos] = newV;
if (!eqComparer.Equals(newV, oldV))
{
pos++;
}
oldV = newV;
}
source.RemoveRange(pos, source.Count - pos);
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: d04d64ff5ae302449a864bfaae8dcfda
timeCreated: 1518622478
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,202 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- Arrays --------------------------------------------
/// <summary>
/// Returns the first element of an array.
/// </summary>
/// <param name="source">The array to return the first element of.</param>
/// <returns>The first element in the specified array.</returns>
public static T FirstF<T>(this T[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
return source[0];
}
/// <summary>
/// Returns the first element in an array that satisfies a specified condition.
/// </summary>
/// <param name="source">An array to return an element from.</param>
/// <param name="predicate">A function to teast each element for a condition.</param>
/// <returns>The first element that satisfies the condition.</returns>
public static T FirstF<T>(this T[] source, Func<T, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
for (int i = 0; i < source.Length; i++)
{
if (predicate(source[i]))
{
return source[i];
}
}
throw Error.NoMatch();
}
/// <summary>
/// Returns the first element of an array, or a default value if the
/// array contains no elements.
/// </summary>
/// <param name="source">The array to return the first element of.</param>
/// <returns>default value if source is empty, otherwise, the first element
/// in source.</returns>
public static T FirstOrDefaultF<T>(this T[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
return default(T);
}
return source[0];
}
/// <summary>
/// Returns the first element of the sequence that satisfies a condition or a
/// default value if no such element is found.
/// </summary>
/// <param name="source">An IEnumerable to return an element from.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns></returns>
public static T FirstOrDefaultF<T>(this T[] source, Func<T, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
for (int i = 0; i < source.Length; i++)
{
if (predicate(source[i]))
{
return source[i];
}
}
return default(T);
}
// -------------------------- Lists --------------------------------------------
/// <summary>
/// Returns the first element of a list
/// </summary>
/// <param name="source">The list to return the first element of.</param>
/// <returns>The first element in the specified list.</returns>
public static T FirstF<T>(this List<T> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
return source[0];
}
/// <summary>
/// Returns the first element in a list that satisfies a specified condition.
/// </summary>
/// <param name="source">An list to return an element from.</param>
/// <param name="predicate">A function to teast each element for a condition.</param>
/// <returns>The first element in the list that satisfies the condition.</returns>
public static T FirstF<T>(this List<T> source, Predicate<T> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var firstIndex = source.FindIndex(predicate);
if (firstIndex == -1)
throw Error.NoMatch();
else
return source[firstIndex];
}
/// <summary>
/// Returns the first element of an array, or a default value if the
/// array contains no elements.
/// </summary>
/// <param name="source">The array to return the first element of.</param>
/// <returns>default value if source is empty, otherwise, the first element
/// in source.</returns>
public static T FirstOrDefaultF<T>(this List<T> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
return default(T);
}
return source[0];
}
/// <summary>
/// Returns the first element of the sequence that satisfies a condition or a
/// default value if no such element is found.
/// </summary>
/// <param name="source">An IEnumerable to return an element from.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns></returns>
public static T FirstOrDefaultF<T>(this List<T> source, Predicate<T> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var firstIndex = source.FindIndex(predicate);
if (firstIndex == -1)
return default(T);
else
return source[firstIndex];
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 7c8f855844813a24f8d07be8c7d7b7c5
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,194 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- Arrays --------------------------------------------
/// <summary>
/// Returns the last element of a sequence.
/// </summary>
/// <param name="source">An sequence to return the last element of.</param>
/// <returns>The value at the last position in the source sequence.</returns>
public static T LastF<T>(this T[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
return source[source.Length - 1];
}
/// <summary>
/// Returns the last element of a sequence that satisfies a specified condition.
/// </summary>
/// <param name="source">A sequence to return an element from.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns></returns>
public static T LastF<T>(this T[] source, Predicate<T> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var lastIndex = Array.FindLastIndex(source, predicate);
if (lastIndex == -1)
throw Error.NoMatch();
else
return source[lastIndex];
}
/// <summary>
/// Returns the last element of a sequence, or a default value if the sequence contains no elements.
/// </summary>
/// <param name="source">An sequence to return the last element of.</param>
/// <returns>default value if the source sequence is empty; otherwise,
/// the last element in the sequence</returns>
public static T LastOrDefaultF<T>(this T[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
return default(T);
}
return source[source.Length - 1];
}
/// <summary>
/// Returns the last element of a sequence that satisfies a condition or a default value if no such element is found.
/// </summary>
/// <param name="source">A sequence to return the last element of.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>default value if the sequence is empty or if no elements pass the test
/// in the predicate function; otherwise, the last element that passes the test in the
/// predicate function.</returns>
public static T LastOrDefaultF<T>(this T[] source, Predicate<T> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var lastIndex = Array.FindLastIndex(source, predicate);
if (lastIndex == -1)
return default(T);
else
return source[lastIndex];
}
// -------------------------- Lists --------------------------------------------
/// <summary>
/// Returns the last element of a sequence.
/// </summary>
/// <param name="source">An sequence to return the last element of.</param>
/// <returns>The value at the last position in the source sequence.</returns>
public static T LastF<T>(this List<T> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
return source[source.Count - 1];
}
/// <summary>
/// Returns the last element of a sequence that satisfies a specified condition.
/// </summary>
/// <param name="source">A sequence to return an element from.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns></returns>
public static T LastF<T>(this List<T> source, Predicate<T> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var lastIndex = source.FindLastIndex(predicate);
if (lastIndex == -1)
throw Error.NoMatch();
else
return source[lastIndex];
}
/// <summary>
/// Returns the last element of a sequence, or a default value if the sequence contains no elements.
/// </summary>
/// <param name="source">An sequence to return the last element of.</param>
/// <returns>default value if the source sequence is empty; otherwise,
/// the last element in the sequence</returns>
public static T LastOrDefaultF<T>(this List<T> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
return default(T);
}
return source[source.Count - 1];
}
/// <summary>
/// Returns the last element of a sequence that satisfies a condition or a default value if no such element is found.
/// </summary>
/// <param name="source">A sequence to return the last element of.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>default value if the sequence is empty or if no elements pass the test
/// in the predicate function; otherwise, the last element that passes the test in the
/// predicate function.</returns>
public static T LastOrDefaultF<T>(this List<T> source, Predicate<T> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var lastIndex = source.FindLastIndex(predicate);
if (lastIndex == -1)
return default(T);
else
return source[lastIndex];
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: aaf88d2684a9a9145ae297d38036fc14
timeCreated: 1518622477
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,779 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
//int, long, float,double, decimal
public static partial class LinqFaster
{
// -------------------------- ARRAYS --------------------------------------------
/// <summary>
/// Returns the maximum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum of.</param>
/// <returns>The maximum value in the sequence</returns>
public static T MaxF<T>(this T[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
Comparer<T> comparer = Comparer<T>.Default;
T r = default(T);
if (r == null)
{
r = source[0];
for (int i = 1; i < source.Length; i++)
{
if (source[i] != null && comparer.Compare(source[i], r) > 0) r = source[i];
}
}
else
{
r = source[0];
for (int i = 1; i < source.Length; i++)
{
if (comparer.Compare(source[i], r) > 0) r = source[i];
}
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static TResult MaxF<T, TResult>(this T[] source, Func<T, TResult> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
Comparer<TResult> comparer = Comparer<TResult>.Default;
TResult r = default(TResult);
if (r == null)
{
r = selector(source[0]);
for (int i = 1; i < source.Length; i++)
{
var v = selector(source[i]);
if (v != null && comparer.Compare(v, r) > 0) r = v;
}
}
else
{
r = selector(source[0]);
for (int i = 1; i < source.Length; i++)
{
var v = selector(source[i]);
if (comparer.Compare(v, r) > 0) r = v;
}
}
return r;
}
/// <summary>
/// Returns the maximum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum of.</param>
/// <returns>The maximum value in the sequence</returns>
public static int MaxF(this int[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
int r = int.MinValue;
for (int i = 0; i < source.Length; i++)
{
if (source[i] > r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static int MaxF<T>(this T[] source, Func<T, int> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
int r = int.MinValue;
for (int i = 0; i < source.Length; i++)
{
var v = selector(source[i]);
if (v > r) r = v;
}
return r;
}
/// <summary>
/// Returns the maximum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum of.</param>
/// <returns>The maximum value in the sequence</returns>
public static long MaxF(this long[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
long r = long.MinValue;
for (int i = 0; i < source.Length; i++)
{
if (source[i] > r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static long MaxF<T>(this T[] source, Func<T, long> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
long r = long.MinValue;
for (int i = 0; i < source.Length; i++)
{
var v = selector(source[i]);
if (v > r) r = v;
}
return r;
}
/// <summary>
/// Returns the maximum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum of.</param>
/// <returns>The maximum value in the sequence</returns>
public static float MaxF(this float[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
float r = source[0];
int startIndex = 0;
for (; startIndex < source.Length; startIndex++)
{
if (!float.IsNaN(source[startIndex]))
{
r = source[startIndex];
break;
}
}
for (int i = startIndex; i < source.Length; i++)
{
if (source[i] > r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static float MaxF<T>(this T[] source, Func<T, float> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
float r = selector(source[0]);
int startIndex = 0;
for (; startIndex < source.Length; startIndex++)
{
var v = selector(source[startIndex]);
if (!float.IsNaN(v))
{
r = v;
break;
}
}
for (int i = startIndex; i < source.Length; i++)
{
var v = selector(source[i]);
if (v > r) r = v;
}
return r;
}
/// <summary>
/// Returns the maximum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum of.</param>
/// <returns>The maximum value in the sequence</returns>
public static double MaxF(this double[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
double r = source[0];
int startIndex = 0;
for (; startIndex < source.Length; startIndex++)
{
if (!double.IsNaN(source[startIndex]))
{
r = source[startIndex];
break;
}
}
for (int i = startIndex; i < source.Length; i++)
{
if (source[i] > r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static double MaxF<T>(this T[] source, Func<T, double> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double r = selector(source[0]);
int startIndex = 0;
for (; startIndex < source.Length; startIndex++)
{
var v = selector(source[startIndex]);
if (!double.IsNaN(v))
{
r = v;
break;
}
}
for (int i = startIndex; i < source.Length; i++)
{
var v = selector(source[i]);
if (v > r) r = v;
}
return r;
}
/// <summary>
/// Returns the maximum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum of.</param>
/// <returns>The maximum value in the sequence</returns>
public static decimal MaxF(this decimal[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
decimal r = decimal.MinValue;
for (int i = 0; i < source.Length; i++)
{
if (source[i] > r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static decimal MaxF<T>(this T[] source, Func<T, decimal> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
decimal r = decimal.MinValue;
for (int i = 0; i < source.Length; i++)
{
var v = selector(source[i]);
if (v > r) r = v;
}
return r;
}
// -------------------------- LISTS --------------------------------------------
/// <summary>
/// Returns the maximum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum of.</param>
/// <returns>The maximum value in the sequence</returns>
public static T MaxF<T>(this List<T> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
Comparer<T> comparer = Comparer<T>.Default;
T r = default(T);
if (r == null)
{
r = source[0];
for (int i = 1; i < source.Count; i++)
{
if (source[i] != null && comparer.Compare(source[i], r) > 0) r = source[i];
}
}
else
{
r = source[0];
for (int i = 1; i < source.Count; i++)
{
if (comparer.Compare(source[i], r) > 0) r = source[i];
}
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static TResult MaxF<T, TResult>(this List<T> source, Func<T, TResult> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
Comparer<TResult> comparer = Comparer<TResult>.Default;
TResult r = default(TResult);
if (r == null)
{
r = selector(source[0]);
for (int i = 1; i < source.Count; i++)
{
var v = selector(source[i]);
if (v != null && comparer.Compare(v, r) > 0) r = v;
}
}
else
{
r = selector(source[0]);
for (int i = 1; i < source.Count; i++)
{
var v = selector(source[i]);
if (comparer.Compare(v, r) > 0) r = v;
}
}
return r;
}
/// <summary>
/// Returns the maximum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum of.</param>
/// <returns>The maximum value in the sequence</returns>
public static int MaxF(this List<int> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
int r = int.MinValue;
for (int i = 0; i < source.Count; i++)
{
if (source[i] > r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static int MaxF<T>(this List<T> source, Func<T, int> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
int r = int.MinValue;
for (int i = 0; i < source.Count; i++)
{
var v = selector(source[i]);
if (v > r) r = v;
}
return r;
}
/// <summary>
/// Returns the maximum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum of.</param>
/// <returns>The maximum value in the sequence</returns>
public static long MaxF(this List<long> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
long r = long.MinValue;
for (int i = 0; i < source.Count; i++)
{
if (source[i] > r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static long MaxF<T>(this List<T> source, Func<T, long> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("source");
}
long r = long.MinValue;
for (int i = 0; i < source.Count; i++)
{
var v = selector(source[i]);
if (v > r) r = v;
}
return r;
}
/// <summary>
/// Returns the maximum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum of.</param>
/// <returns>The maximum value in the sequence</returns>
public static float MaxF(this List<float> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
float r = source[0];
int startIndex = 0;
for (; startIndex < source.Count; startIndex++)
{
if (!float.IsNaN(source[startIndex]))
{
r = source[startIndex];
break;
}
}
for (int i = startIndex; i < source.Count; i++)
{
if (source[i] > r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static float MaxF<T>(this List<T> source, Func<T, float> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
float r = selector(source[0]);
int startIndex = 0;
for (; startIndex < source.Count; startIndex++)
{
var v = selector(source[startIndex]);
if (!float.IsNaN(v))
{
r = v;
break;
}
}
for (int i = startIndex; i < source.Count; i++)
{
var v = selector(source[i]);
if (v > r) r = v;
}
return r;
}
/// <summary>
/// Returns the maximum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum of.</param>
/// <returns>The maximum value in the sequence</returns>
public static double MaxF(this List<double> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
double r = source[0];
int startIndex = 0;
for (; startIndex < source.Count; startIndex++)
{
if (!double.IsNaN(source[startIndex]))
{
r = source[startIndex];
break;
}
}
for (int i = startIndex; i < source.Count; i++)
{
if (source[i] > r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static double MaxF<T>(this List<T> source, Func<T, double> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double r = selector(source[0]);
int startIndex = 0;
for (; startIndex < source.Count; startIndex++)
{
var v = selector(source[startIndex]);
if (!double.IsNaN(v))
{
r = v;
break;
}
}
for (int i = startIndex; i < source.Count; i++)
{
var v = selector(source[i]);
if (v > r) r = v;
}
return r;
}
/// <summary>
/// Returns the maximum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum of.</param>
/// <returns>The maximum value in the sequence</returns>
public static decimal MaxF(this List<decimal> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
decimal r = decimal.MinValue;
for (int i = 0; i < source.Count; i++)
{
if (source[i] > r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static decimal MaxF<T>(this List<T> source, Func<T, decimal> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
decimal r = decimal.MinValue;
for (int i = 0; i < source.Count; i++)
{
var v = selector(source[i]);
if (v > r) r = v;
}
return r;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: c48e3dffd69eb0a4e8e135b38d3d9bf0
timeCreated: 1518622477
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,711 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
//int, long, float,double, decimal
public static partial class LinqFaster
{
// -------------------------- ARRAYS --------------------------------------------
/// <summary>
/// Returns the minimum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the minimum of.</param>
/// <returns>The minimum value in the sequence</returns>
public static T MinF<T>(this T[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
Comparer<T> comparer = Comparer<T>.Default;
T r = default(T);
if (r == null)
{
r = source[0];
for (int i = 1; i < source.Length; i++)
{
if (source[i] != null && comparer.Compare(source[i], r) < 0) r = source[i];
}
}
else
{
r = source[0];
for (int i = 1; i < source.Length; i++)
{
if (comparer.Compare(source[i], r) < 0) r = source[i];
}
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static TResult MinF<T, TResult>(this T[] source, Func<T, TResult> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
Comparer<TResult> comparer = Comparer<TResult>.Default;
TResult r = default(TResult);
if (r == null)
{
r = selector(source[0]);
for (int i = 1; i < source.Length; i++)
{
var v = selector(source[i]);
if (v != null && comparer.Compare(v, r) < 0) r = v;
}
}
else
{
r = selector(source[0]);
for (int i = 1; i < source.Length; i++)
{
var v = selector(source[i]);
if (comparer.Compare(v, r) < 0) r = v;
}
}
return r;
}
/// <summary>
/// Returns the minimum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the minimum of.</param>
/// <returns>The minimum value in the sequence</returns>
public static int MinF(this int[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
int r = int.MaxValue;
for (int i = 0; i < source.Length; i++)
{
if (source[i] < r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static int MinF<T>(this T[] source, Func<T, int> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
int r = int.MaxValue;
for (int i = 0; i < source.Length; i++)
{
var v = selector(source[i]);
if (v < r) r = v;
}
return r;
}
/// <summary>
/// Returns the minimum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the minimum of.</param>
/// <returns>The minimum value in the sequence</returns>
public static long MinF(this long[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
long r = long.MaxValue;
for (int i = 0; i < source.Length; i++)
{
if (source[i] < r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static long MinF<T>(this T[] source, Func<T, long> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
long r = long.MaxValue;
for (int i = 0; i < source.Length; i++)
{
var v = selector(source[i]);
if (v < r) r = v;
}
return r;
}
/// <summary>
/// Returns the minimum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the minimum of.</param>
/// <returns>The minimum value in the sequence</returns>
public static float MinF(this float[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
float r = float.MaxValue;
for (int i = 0; i < source.Length; i++)
{
if (source[i] < r) r = source[i];
else if (float.IsNaN(source[i])) return source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static float MinF<T>(this T[] source, Func<T, float> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
float r = float.MaxValue;
for (int i = 0; i < source.Length; i++)
{
var v = selector(source[i]);
if (v < r) r = v;
else if (float.IsNaN(v)) return v;
}
return r;
}
/// <summary>
/// Returns the minimum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the minimum of.</param>
/// <returns>The minimum value in the sequence</returns>
public static double MinF(this double[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
double r = double.MaxValue;
for (int i = 0; i < source.Length; i++)
{
if (source[i] < r) r = source[i];
else if (double.IsNaN(source[i])) return source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static double MinF<T>(this T[] source, Func<T, double> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double r = double.MaxValue;
for (int i = 0; i < source.Length; i++)
{
var v = selector(source[i]);
if (v < r) r = v;
else if (double.IsNaN(v)) return v;
}
return r;
}
/// <summary>
/// Returns the minimum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the minimum of.</param>
/// <returns>The minimum value in the sequence</returns>
public static decimal MinF(this decimal[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
decimal r = decimal.MaxValue;
for (int i = 0; i < source.Length; i++)
{
if (source[i] < r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static decimal MinF<T>(this T[] source, Func<T, decimal> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
decimal r = decimal.MaxValue;
for (int i = 0; i < source.Length; i++)
{
var v = selector(source[i]);
if (v < r) r = v;
}
return r;
}
// -------------------------- LISTS --------------------------------------------
/// <summary>
/// Returns the minimum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the minimum of.</param>
/// <returns>The minimum value in the sequence</returns>
public static T MinF<T>(this List<T> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
Comparer<T> comparer = Comparer<T>.Default;
T r = default(T);
if (r == null)
{
r = source[0];
for (int i = 1; i < source.Count; i++)
{
if (source[i] != null && comparer.Compare(source[i], r) < 0) r = source[i];
}
}
else
{
r = source[0];
for (int i = 1; i < source.Count; i++)
{
if (comparer.Compare(source[i], r) < 0) r = source[i];
}
}
return r;
}
/// <summary>
/// Returns the minimum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the minimum of.</param>
/// <returns>The minimum value in the sequence</returns>
public static int MinF(this List<int>source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
int r = int.MaxValue;
for (int i = 0; i < source.Count; i++)
{
if (source[i] < r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static int MinF<T>(this List<T> source, Func<T, int> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
int r = int.MaxValue;
for (int i = 0; i < source.Count; i++)
{
var v = selector(source[i]);
if (v < r) r = v;
}
return r;
}
/// <summary>
/// Returns the minimum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the minimum of.</param>
/// <returns>The minimum value in the sequence</returns>
public static long MinF(this List<long> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
long r = long.MaxValue;
for (int i = 0; i < source.Count; i++)
{
if (source[i] < r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static long MinF<T>(this List<T> source, Func<T, long> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("source");
}
long r = long.MaxValue;
for (int i = 0; i < source.Count; i++)
{
var v = selector(source[i]);
if (v < r) r = v;
}
return r;
}
/// <summary>
/// Returns the minimum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the minimum of.</param>
/// <returns>The minimum value in the sequence</returns>
public static float MinF(this List<float> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
float r = float.MaxValue;
for (int i = 0; i < source.Count; i++)
{
if (source[i] < r) r = source[i];
else if (float.IsNaN(source[i])) return source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static float MinF<T>(this List<T> source, Func<T, float> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
float r = float.MaxValue;
for (int i = 0; i < source.Count; i++)
{
var v = selector(source[i]);
if (v < r) r = v;
else if (float.IsNaN(v)) return v;
}
return r;
}
/// <summary>
/// Returns the minimum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the minimum of.</param>
/// <returns>The minimum value in the sequence</returns>
public static double MinF(this List<double> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
double r = double.MaxValue;
for (int i = 0; i < source.Count; i++)
{
if (source[i] < r) r = source[i];
else if (double.IsNaN(source[i])) return source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static double MinF<T>(this List<T> source, Func<T, double> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double r = double.MaxValue;
for (int i = 0; i < source.Count; i++)
{
var v = selector(source[i]);
if (v < r) r = v;
else if (double.IsNaN(v)) return v;
}
return r;
}
/// <summary>
/// Returns the minimum value in a sequence of values.
/// </summary>
/// <param name="source">A sequence of values to determine the minimum of.</param>
/// <returns>The minimum value in the sequence</returns>
public static decimal MinF(this List<decimal> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
decimal r = decimal.MaxValue;
for (int i = 0; i < source.Count; i++)
{
if (source[i] < r) r = source[i];
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static decimal MinF<T>(this List<T> source, Func<T, decimal> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
decimal r = decimal.MaxValue;
for (int i = 0; i < source.Count; i++)
{
var v = selector(source[i]);
if (v < r) r = v;
}
return r;
}
/// <summary>
/// Invokes a transform function on each element of a sequence and returns the maximum value.
/// </summary>
/// <param name="source">A sequence of values to determine the maximum value of.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The maximum value in the transform of the sequence.</returns>
public static TResult MinF<T, TResult>(this List<T> source, Func<T, TResult> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
Comparer<TResult> comparer = Comparer<TResult>.Default;
TResult r = default(TResult);
if (r == null)
{
r = selector(source[0]);
for (int i = 1; i < source.Count; i++)
{
var v = selector(source[i]);
if (v != null && comparer.Compare(v, r) < 0) r = v;
}
}
else
{
r = selector(source[0]);
for (int i = 1; i < source.Count; i++)
{
var v = selector(source[i]);
if (comparer.Compare(v, r) < 0) r = v;
}
}
return r;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: e778ffbe0914c7c4e88564ff2ba27fff
timeCreated: 1518622478
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,144 @@
using System;
using System.Collections.Generic;
using JM.LinqFaster.Utils;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
/// <summary>
/// Sorts the elements of a sequence in ascending order according to a key.
/// Unlike standard Linq NOT a stable sort.
/// </summary>
/// <param name="source">A sequence of values to order.</param>
/// <param name="keySelector">A function to extract a key from an element.</param>
/// <param name="comparer">A Comparer to compare keys.</param>
/// <returns>A sequence whose alements are ordered according to a key</returns>
public static TSource[] OrderByF<TSource, TKey>(this TSource[] source, Func<TSource, TKey> keySelector,IComparer<TKey> comparer = null)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (keySelector == null)
{
throw Error.ArgumentNull("keySelector");
}
if (comparer == null)
{
comparer = Comparer<TKey>.Default;
}
var keys = new TKey[source.Length];
for (int i = 0; i < keys.Length; i++)
{
keys[i] = keySelector(source[i]);
}
var result = (TSource[])source.Clone();
Array.Sort(keys,result,comparer);
return result;
}
/// <summary>
/// Sorts the elements of a sequence in descending order according to a key.
/// Unlike standard Linq NOT a stable sort.
/// </summary>
/// <param name="source">A sequence of values to order.</param>
/// <param name="keySelector">A function to extract a key from an element.</param>
/// <param name="comparer">A Comparer to compare keys.</param>
/// <returns>A sequence whose alements are ordered according to a key</returns>
public static TSource[] OrderByDescendingF<TSource, TKey>(this TSource[] source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer = null) {
if (source == null) {
throw Error.ArgumentNull("source");
}
if (keySelector == null) {
throw Error.ArgumentNull("keySelector");
}
if (comparer == null) {
comparer = Comparer<TKey>.Default;
}
var keys = new TKey[source.Length];
for (int i = 0; i < keys.Length; i++) {
keys[i] = keySelector(source[i]);
}
var result = (TSource[])source.Clone();
Array.Sort(keys, result, comparer.Reverse());
return result;
}
// ---------------------- Lists
/// <summary>
/// Sorts the elements of a sequence in ascending order according to a key.
/// Unlike standard Linq NOT a stable sort.
/// </summary>
/// <param name="source">A sequence of values to order.</param>
/// <param name="keySelector">A function to extract a key from an element.</param>
/// <param name="comparer">A Comparer to compare keys.</param>
/// <returns>A sequence whose alements are ordered according to a key</returns>
public static List<TSource> OrderByF<TSource, TKey>(this List<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer = null)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (keySelector == null)
{
throw Error.ArgumentNull("keySelector");
}
if (comparer == null)
{
comparer = Comparer<TKey>.Default;
}
var result = new List<TSource>(source);
var lambdaComparer = new LambdaComparer<TSource, TKey>(keySelector, comparer);
result.Sort(lambdaComparer);
return result;
}
/// <summary>
/// Sorts the elements of a sequence in descending order according to a key.
/// Unlike standard Linq NOT a stable sort.
/// </summary>
/// <param name="source">A sequence of values to order.</param>
/// <param name="keySelector">A function to extract a key from an element.</param>
/// <param name="comparer">A Comparer to compare keys.</param>
/// <returns>A sequence whose alements are ordered according to a key</returns>
public static List<TSource> OrderByDescendingF<TSource, TKey>(this List<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer = null) {
if (source == null) {
throw Error.ArgumentNull("source");
}
if (keySelector == null) {
throw Error.ArgumentNull("keySelector");
}
if (comparer == null) {
comparer = Comparer<TKey>.Default;
}
var result = new List<TSource>(source);
var lambdaComparer = new ReverseLambdaComparer<TSource, TKey>(keySelector, comparer);
result.Sort(lambdaComparer);
return result;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 0905671e8837b8746ab9d2540689f16c
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,56 @@
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
/// <summary>
/// Generates a sequence of integral numbers within a specified range.
/// </summary>
/// <param name="start">The value of the first integer in the sequence.</param>
/// <param name="count">The number of sequential integers to generate.</param>
/// <returns>A sequence that contains a range of sequential integral numbers.</returns>
public static int[] RangeArrayF(int start, int count)
{
long max = ((long)start) + count - 1;
if (count < 0 || max > int.MaxValue)
{
throw Error.ArgumentOutOfRange("count");
}
int[] result = new int[count];
for (int i = 0; i < result.Length; i++)
{
result[i] = i + start;
}
return result;
}
/// <summary>
/// Generates a sequence of integral numbers within a specified range.
/// </summary>
/// <param name="start">The value of the first integer in the sequence.</param>
/// <param name="count">The number of sequential integers to generate.</param>
/// <returns>A sequence that contains a range of sequential integral numbers.</returns>
public static List<int> RangeListF(int start, int count)
{
long max = ((long)start) + count - 1;
if (count < 0 || max > int.MaxValue)
{
throw Error.ArgumentOutOfRange("count");
}
var result = new List<int>(count);
for (int i = 0; i < count; i++)
{
result.Add(i + start);
}
return result;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 2b57c73286e4b784a897b514585dcdc2
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,46 @@

using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// ------------------------ Arrays ---------------------------
/// <summary>
/// Generates a sequence that contains one repeated value.
/// </summary>
/// <param name="element">The value to be repeated.</param>
/// <param name="count">The number of times to repeat the value in the generated sequence.</param>
/// <returns>A sequence that contains a repeated value</returns>
public static T[] RepeatArrayF<T>(T element, int count)
{
var result = new T[count];
for (int i = 0; i < result.Length; i++)
{
result[i] = element;
}
return result;
}
// ------------------------ Lists ---------------------------
/// <summary>
/// Generates a sequence that contains one repeated value.
/// </summary>
/// <param name="element">The value to be repeated.</param>
/// <param name="count">The number of times to repeat the value in the generated sequence.</param>
/// <returns>A sequence that contains a repeated value</returns>
public static List<T> RepeatListF<T>(T element, int count)
{
var result = new List<T>(count);
for (int i = 0; i < count; i++)
{
result.Add(element);
}
return result;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: a9a067c2d04a41e499adfde8c8ab6956
timeCreated: 1518622477
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
/// <summary>
/// Inverts the order of the elements in a sequence.
/// </summary>
/// <param name="source">A sequence of values to reverse.</param>
/// <returns>A sequence whose elements correspond to those of the input sequence in reverse order.</returns>
public static T[] ReverseF<T>(this T[] source)
{
var result = new T[source.Length];
long lenLessOne = source.Length - 1;
for (int i = 0; i < result.Length; i++)
{
result[i] = source[lenLessOne - i];
}
return result;
}
/// <summary>
/// Inverts the order of the elements in a sequence in place.
/// </summary>
/// <param name="source">A sequence of values to reverse.</param>
public static void ReverseInPlaceF<T>(this T[] source)
{
Array.Reverse(source);
}
/// <summary>
/// Inverts the order of the elements in a sequence.
/// </summary>
/// <param name="source">A sequence of values to reverse.</param>
/// <returns>A sequence whose elements correspond to those of the input sequence in reverse order.</returns>
public static List<T> ReverseF<T>(this List<T> source)
{
var result = new List<T>(source.Count);
for (int i = source.Count - 1; i >= 0; i--)
{
result.Add(source[i]);
}
return result;
}
/// <summary>
/// Inverts the order of the elements in a sequence in place.
/// </summary>
/// <param name="source">A sequence of values to reverse.</param>
public static void ReverseInPlaceF<T>(this List<T> source)
{
source.Reverse();
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 060a1817dc4b6a14997095dfc23c4d3b
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,219 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- ARRAYS --------------------------------------------
/// <summary>
/// Projects each element of a sequence into a new form in place.
/// </summary>
/// <param name="source">A sequence of values to invoke a transform function on (map).</param>
/// <param name="selector">A transform function to apply (map) to each element.</param>
public static void SelectInPlaceF<T>(this T[] source, Func<T,T> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
for (int i = 0; i < source.Length; i++)
{
source[i] = selector(source[i]);
}
}
/// <summary>
/// Projects each element of a sequence into a new form, in place, by incorporating the element's index.
/// </summary>
/// <param name="source">A sequence of values to invoke a transform function on.</param>
/// <param name="selector">A transform function to apply to each source element; the second parameter of the function represents the index of the source element.</param>
public static void SelectInPlaceF<T>(this T[] source, Func<T, int, T> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
for (int i = 0; i < source.Length; i++)
{
source[i] = selector(source[i], i);
}
}
/// <summary>
/// Projects each element of a sequence into a new form. (map in every other language)
/// </summary>
/// <param name="source">A sequence of values to invoke a transform function on (map).</param>
/// <param name="selector">A transform function to apply (map) to each element.</param>
/// <returns>A sequence whose elements are the result of invoking the transform function on each element (mapping) of source.</returns>
public static TResult[] SelectF<T, TResult>(this T[] source, Func<T, TResult> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
var r = new TResult[source.Length];
for (int i = 0; i < source.Length; i++)
{
r[i] = selector(source[i]);
}
return r;
}
/// <summary>
/// Projects each element of a sequence into a new form by incorporating the element's index.
/// </summary>
/// <param name="source">A sequence of values to invoke a transform function on.</param>
/// <param name="selector">A transform function to apply to each source element; the second parameter of the function represents the index of the source element.</param>
/// <returns>A sequence whose elements are the result of invoking the transform function on each element of source.</returns>
public static TResult[] SelectF<T, TResult>(this T[] source, Func<T, int, TResult> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
var r = new TResult[source.Length];
for (int i = 0; i < source.Length; i++)
{
r[i] = selector(source[i], i);
}
return r;
}
// -------------------------- LISTS --------------------------------------------
/// <summary>
/// Projects each element of a sequence into a new form in place.
/// </summary>
/// <param name="source">A sequence of values to invoke a transform function on (map).</param>
/// <param name="selector">A transform function to apply (map) to each element.</param>
public static void SelectInPlaceF<T>(this List<T> source, Func<T, T> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
for (int i = 0; i < source.Count; i++)
{
source[i] = selector(source[i]);
}
}
/// <summary>
/// Projects each element of a sequence into a new form, in place, by incorporating the element's index.
/// </summary>
/// <param name="source">A sequence of values to invoke a transform function on.</param>
/// <param name="selector">A transform function to apply to each source element; the second parameter of the function represents the index of the source element.</param>
public static void SelectInPlaceF<T>(this List<T> source, Func<T, int, T> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
for (int i = 0; i < source.Count; i++)
{
source[i] = selector(source[i], i);
}
}
/// <summary>
/// Projects each element of a sequence into a new form. (map in every other language)
/// </summary>
/// <param name="source">A sequence of values to invoke a transform function on (map).</param>
/// <param name="selector">A transform function to apply (map) to each element.</param>
/// <returns>A sequence whose elements are the result of invoking the transform function on each element (mapping) of source.</returns>
public static List<TResult> SelectF<T, TResult>(this List<T> source, Func<T, TResult> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
var r = new List<TResult>(source.Count);
for (int i = 0; i < source.Count; i++)
{
r.Add(selector(source[i]));
}
return r;
}
/// <summary>
/// Projects each element of a sequence into a new form by incorporating the element's index.
/// </summary>
/// <param name="source">A sequence of values to invoke a transform function on.</param>
/// <param name="selector">A transform function to apply to each source element; the second parameter of the function represents the index of the source element.</param>
/// <returns>A sequence whose elements are the result of invoking the transform function on each element of source.</returns>
public static List<TResult> SelectF<T, TResult>(this List<T> source, Func<T, int, TResult> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
var r = new List<TResult>(source.Count);
for (int i = 0; i < source.Count; i++)
{
r.Add(selector(source[i],i));
}
return r;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 26eaf75f376ca7147a6c161177592aca
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,136 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- Arrays --------------------------------------------
/// <summary>
/// Projects each element of a sequence to another sequence and flattens the resulting sequences into one sequence.
/// Yo dawg, I heard you like sequences.
/// </summary>
/// <param name="source">A sequence of values to project.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>A sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.</returns>
public static TResult[] SelectManyF<TSource, TResult>(this TSource[] source, Func<TSource, TResult[]> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
var result = new List<TResult>(source.Length);
for (int i = 0; i < source.Length; i++)
{
var va = selector(source[i]);
for (int j = 0; j < va.Length; j++)
{
result.Add(va[j]);
}
}
return result.ToArray();
}
/// <summary>
/// Projects each element of a sequence to another sequence and flattens the resulting sequences into one sequence
/// utilizing the index of each element.
/// </summary>
/// <param name="source">A sequence of values to project.</param>
/// <param name="selector">A transform function to apply to each element and it's index.</param>
/// <returns>A sequence whose elements are the result of invoking the one-to-many transform function on each element and index of the input sequence.</returns>
public static TResult[] SelectManyF<TSource, TResult>(this TSource[] source, Func<TSource, int, TResult[]> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
var result = new List<TResult>(source.Length);
for (int i = 0; i < source.Length; i++)
{
var va = selector(source[i], i);
for (int j = 0; j < va.Length; j++)
{
result.Add(va[j]);
}
}
return result.ToArray();
}
// -------------------------- LISTS --------------------------------------------
/// <summary>
/// Projects each element of a sequence to another sequence and flattens the resulting sequences into one sequence.
/// Yo dawg, I heard you like sequences.
/// </summary>
/// <param name="source">A sequence of values to project.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>A sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.</returns>
public static List<TResult> SelectManyF<TSource, TResult>(this List<TSource> source, Func<TSource, List<TResult>> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
var result = new List<TResult>(source.Count);
for (int i = 0; i < source.Count; i++)
{
var va = selector(source[i]);
for (int j = 0; j < va.Count; j++)
{
result.Add(va[j]);
}
}
return result;
}
/// <summary>
/// Projects each element of a sequence to another sequence and flattens the resulting sequences into one sequence
/// utilizing the index of each element.
/// </summary>
/// <param name="source">A sequence of values to project.</param>
/// <param name="selector">A transform function to apply to each element and it's index.</param>
/// <returns>A sequence whose elements are the result of invoking the one-to-many transform function on each element and index of the input sequence.</returns>
public static List<TResult> SelectManyF<TSource, TResult>(this List<TSource> source, Func<TSource, int, List<TResult>> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
var result = new List<TResult>(source.Count);
for (int i = 0; i < source.Count; i++)
{
var va = selector(source[i], i);
for (int j = 0; j < va.Count; j++)
{
result.Add(va[j]);
}
}
return result;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 8c94982c6c13eb2479b832d2210b5451
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,142 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- ARRAYS --------------------------------------------
/// <summary>
/// Combines Select and Where into a single call for optimal
/// performance.
/// </summary>
/// <param name="source">The input sequence to filter and select</param>
/// <param name="selector">The transformation to apply before filtering.</param>
/// <param name="predicate">The predicate with which to filter result.</param>
/// <returns>A seqence transformed and then filtered by selector and predicate.</returns>
public static TResult[] SelectWhereF<T, TResult>(this T[] source, Func<T, TResult> selector, Func<TResult, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var result = new TResult[source.Length];
int idx = 0;
for (int i = 0; i < source.Length; i++)
{
var s = selector(source[i]);
if (predicate(s))
{
result[idx] = s;
idx++;
}
}
Array.Resize(ref result, idx);
return result;
}
/// <summary>
/// Combines Select and Where with indexes into a single call for optimal
/// performance.
/// </summary>
/// <param name="source">The input sequence to filter and select</param>
/// <param name="selector">The transformation with index to apply before filtering.</param>
/// <param name="predicate">The predicate with index with which to filter result.</param>
/// <returns>A seqence transformed and then filtered by selector and predicate with indexes.</returns>
public static TResult[] SelectWhereF<T, TResult>(this T[] source, Func<T, int, TResult> selector, Func<TResult, int, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var result = new TResult[source.Length];
int idx = 0;
for (int i = 0; i < source.Length; i++)
{
var s = selector(source[i], i);
if (predicate(s, i))
{
result[idx] = s;
idx++;
}
}
Array.Resize(ref result, idx);
return result;
}
// -------------------------- LISTS --------------------------------------------
/// <summary>
/// Combines Select and Where into a single call for optimal
/// performance.
/// </summary>
/// <param name="source">The input sequence to filter and select</param>
/// <param name="selector">The transformation to apply before filtering.</param>
/// <param name="predicate">The predicate with which to filter result.</param>
/// <returns>A seqence transformed and then filtered by selector and predicate.</returns>
public static List<TResult> SelectWhereF<T, TResult>(this List<T> source, Func<T, TResult> selector, Func<TResult, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var r = new List<TResult>();
for (int i = 0; i < source.Count; i++)
{
var s = selector(source[i]);
if (predicate(s)) r.Add(s);
}
return r;
}
/// <summary>
/// Combines Select and Where with indexes into a single call for optimal
/// performance.
/// </summary>
/// <param name="source">The input sequence to filter and select</param>
/// <param name="selector">The transformation with index to apply before filtering.</param>
/// <param name="predicate">The predicate with index with which to filter result.</param>
/// <returns>A seqence transformed and then filtered by selector and predicate with indexes.</returns>
public static List<TResult> SelectWhereF<T, TResult>(this List<T> source, Func<T, int, TResult> selector, Func<TResult, int, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var r = new List<TResult>();
for (int i = 0; i < source.Count; i++)
{
var s = selector(source[i], i);
if (predicate(s, i)) r.Add(s);
}
return r;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: d0a9e823f84f85049ae653bf4fc8c7b9
timeCreated: 1518622478
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,153 @@
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
/// <summary>
/// Determines whether two sequences are equal by comparing the elements by using the
/// provided comparer or the default equality comparer for their type if none is provided.
/// </summary>
/// <param name="first">A sequence to compare to second.</param>
/// <param name="second">A sequence to compare to first.</param>
/// <param name="comparer">An optional Comparer to use for the comparison.</param>
/// <returns>true of the two sources are of equal length and their corresponding
/// elements are equal according to the equality comparer. Otherwise, false.</returns>
public static bool SequenceEqualF<T>(T[] first, T[] second, IEqualityComparer<T> comparer = null)
{
if (comparer == null)
{
comparer = EqualityComparer<T>.Default;
}
if (first == null)
{
throw Error.ArgumentNull("first");
}
if (second == null)
{
throw Error.ArgumentNull("second");
}
if (first.Length != second.Length) return false;
for (int i = 0; i < first.Length; i++)
{
if (!comparer.Equals(first[i], second[i])) return false;
}
return true;
}
/// <summary>
/// Determines whether two sequences are equal by comparing the elements by using the
/// provided comparer or the default equality comparer for their type if none is provided.
/// </summary>
/// <param name="first">A sequence to compare to second.</param>
/// <param name="second">A sequence to compare to first.</param>
/// <param name="comparer">An optional Comparer to use for the comparison.</param>
/// <returns>true of the two sources are of equal length and their corresponding
/// elements are equal according to the equality comparer. Otherwise, false.</returns>
public static bool SequenceEqualF<T>(List<T> first, List<T> second, IEqualityComparer<T> comparer = null)
{
if (comparer == null)
{
comparer = EqualityComparer<T>.Default;
}
if (first == null)
{
throw Error.ArgumentNull("first");
}
if (second == null)
{
throw Error.ArgumentNull("second");
}
if (first.Count != second.Count) return false;
for (int i = 0; i < first.Count; i++)
{
if (!comparer.Equals(first[i], second[i])) return false;
}
return true;
}
/// <summary>
/// Determines whether two sequences are equal by comparing the elements by using the
/// provided comparer or the default equality comparer for their type if none is provided.
/// </summary>
/// <param name="first">A sequence to compare to second.</param>
/// <param name="second">A sequence to compare to first.</param>
/// <param name="comparer">An optional Comparer to use for the comparison.</param>
/// <returns>true of the two sources are of equal length and their corresponding
/// elements are equal according to the equality comparer. Otherwise, false.</returns>
public static bool SequenceEqualF<T>(T[] first, List<T> second, IEqualityComparer<T> comparer = null)
{
if (comparer == null)
{
comparer = EqualityComparer<T>.Default;
}
if (first == null)
{
throw Error.ArgumentNull("first");
}
if (second == null)
{
throw Error.ArgumentNull("second");
}
if (first.Length != second.Count) return false;
for (int i = 0; i < first.Length; i++)
{
if (!comparer.Equals(first[i], second[i])) return false;
}
return true;
}
/// <summary>
/// Determines whether two sequences are equal by comparing the elements by using the
/// provided comparer or the default equality comparer for their type if none is provided.
/// </summary>
/// <param name="first">A sequence to compare to second.</param>
/// <param name="second">A sequence to compare to first.</param>
/// <param name="comparer">An optional Comparer to use for the comparison.</param>
/// <returns>true of the two sources are of equal length and their corresponding
/// elements are equal according to the equality comparer. Otherwise, false.</returns>
public static bool SequenceEqualF<T>(List<T> first, T[] second, IEqualityComparer<T> comparer = null)
{
if (comparer == null)
{
comparer = EqualityComparer<T>.Default;
}
if (first == null)
{
throw Error.ArgumentNull("first");
}
if (second == null)
{
throw Error.ArgumentNull("second");
}
if (first.Count != second.Length) return false;
for (int i = 0; i < first.Count; i++)
{
if (!comparer.Equals(first[i], second[i])) return false;
}
return true;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 7fe4476c042c98d4dbae1292ea8da673
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,275 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// --------------------------- Arrays ----------------------------
/// <summary>
/// Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
/// </summary>
/// <param name="source">A sequence to return the single element of</param>
/// <returns>The single element of the input sequence or default if no elements exist.</returns>
public static T SingleF<T>(this T[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
throw Error.NoElements();
}
if (source.Length > 1) {
throw Error.MoreThanOneElement();
}
return source[0];
}
/// <summary>
/// Returns the only element of a sequence, or the default if no elements exist, and throws an exception if there is not exactly one element in the sequence.
/// </summary>
/// <param name="source">A sequence to return the single element of</param>
/// <returns>The single element of the input sequence</returns>
public static T SingleOrDefaultF<T>(this T[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Length == 0)
{
return default(T);
}
if (source.Length > 1) {
throw Error.MoreThanOneElement();
}
return source[0];
}
/// <summary>
/// Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.
/// </summary>
/// <param name="source">A sequence to return a single element from.</param>
/// <param name="predicate">A function to test an element for a condition.</param>
/// <returns>The single element of the input sequence that satisfies a condition.</returns>
public static T SingleF<T>(this T[] source, Func<T, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
T result = default(T);
bool foundMatch = false;
for (int i = 0; i < source.Length; i++)
{
if (predicate(source[i]))
{
if (foundMatch)
{
throw Error.MoreThanOneMatch();
}
result = source[i];
foundMatch = true;
}
}
if (foundMatch)
{
return result;
}
else
{
throw Error.NoMatch();
}
}
/// <summary>
/// Returns the only element of a sequence that satisfies a specified condition, or a default value if
/// no such element exists, and throws an exception if more than one such element exists.
/// </summary>
/// <param name="source">A sequence to return a single element from.</param>
/// <param name="predicate">A function to test an element for a condition.</param>
/// <returns>The single element of the input sequence that satisfies a condition or default value if no such element is found.</returns>
public static T SingleOrDefaultF<T>(this T[] source, Func<T, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
T result = default(T);
bool foundMatch = false;
for (int i = 0; i < source.Length; i++)
{
if (predicate(source[i]))
{
if (foundMatch)
{
throw Error.MoreThanOneMatch();
}
result = source[i];
foundMatch = true;
}
}
return result;
}
// --------------------------- Lists ----------------------------
/// <summary>
/// Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
/// </summary>
/// <param name="source">A sequence to return the single element of</param>
/// <returns>The single element of the input sequence</returns>
public static T SingleF<T>(this List<T> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
throw Error.NoElements();
}
if (source.Count > 1) {
throw Error.MoreThanOneElement();
}
return source[0];
}
/// <summary>
/// Returns the only element of a sequence, or default if no elements exist, and throws an exception if there is not exactly one element in the sequence.
/// </summary>
/// <param name="source">A sequence to return the single element of</param>
/// <returns>The single element of the input sequence or default if no elements exist.</returns>
public static T SingleOrDefaultF<T>(this List<T> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (source.Count == 0)
{
return default(T);
}
if (source.Count > 1) {
throw Error.MoreThanOneElement();
}
return source[0];
}
/// <summary>
/// Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.
/// </summary>
/// <param name="source">A sequence to return a single element from.</param>
/// <param name="predicate">A function to test an element for a condition.</param>
/// <returns>The single element of the input sequence that satisfies a condition.</returns>
public static T SingleF<T>(this List<T> source, Func<T, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
T result = default(T);
bool foundMatch = false;
for (int i = 0; i < source.Count; i++)
{
if (predicate(source[i]))
{
if (foundMatch)
{
throw Error.MoreThanOneMatch();
}
result = source[i];
foundMatch = true;
}
}
if (foundMatch)
{
return result;
}
else
{
throw Error.NoMatch();
}
}
/// <summary>
/// Returns the only element of a sequence that satisfies a specified condition, or a default value if
/// no such element exists, and throws an exception if more than one such element exists.
/// </summary>
/// <param name="source">A sequence to return a single element from.</param>
/// <param name="predicate">A function to test an element for a condition.</param>
/// <returns>The single element of the input sequence that satisfies a condition or default value if no such element is found.</returns>
public static T SingleOrDefaultF<T>(this List<T> source, Func<T, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
T result = default(T);
bool foundMatch = false;
for (int i = 0; i < source.Count; i++)
{
if (predicate(source[i]))
{
if (foundMatch)
{
throw Error.MoreThanOneMatch();
}
result = source[i];
foundMatch = true;
}
}
return result;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 50d60901bb3bf014e8d8e1ceef8c4741
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
/// <summary>
/// Bypasses a specified number of elements in a sequence and then returns the remaining elements.
/// </summary>
/// <param name="source">A sequence to return elements from.</param>
/// <param name="count">The number of elements to skip before returning the remaining elements.</param>
/// <returns>A sequence that contains the elements that occur after the specified index in the input sequence.</returns>
public static T[] SkipF<T>(this T[] source, int count)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (count < 0)
{
count = 0;
}
else if (count > source.Length)
{
return new T[0];
}
var result = new T[source.Length - count];
Array.Copy(source, count, result, 0, result.Length);
return result;
}
/// <summary>
/// Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.
/// </summary>
/// <param name="source">A sequence to return elements from.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>A sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.</returns>
public static T[] SkipWhileF<T>(this T[] source, Func<T, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
int i = 0;
for (; i < source.Length; i++)
{
if (!predicate(source[i])) break;
}
var result = new T[source.Length - i];
Array.Copy(source, i, result, 0, result.Length);
return result;
}
// ------------- Lists ----------------
/// <summary>
/// Bypasses a specified number of elements in a sequence and then returns the remaining elements.
/// </summary>
/// <param name="source">A sequence to return elements from.</param>
/// <param name="count">The number of elements to skip before returning the remaining elements.</param>
/// <returns>A sequence that contains the elements that occur after the specified index in the input sequence.</returns>
public static List<T> SkipF<T>(this List<T> source, int count)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (count < 0)
{
count = 0;
}
else if (count > source.Count)
{
return new List<T>();
}
var result = new List<T>(source.Count - count);
for (int i = count; i < source.Count; i++)
{
result.Add(source[i]);
}
return result;
}
/// <summary>
/// Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.
/// </summary>
/// <param name="source">A sequence to return elements from.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>A sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.</returns>
public static List<T> SkipWhileF<T>(this List<T> source, Func<T, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
int i = 0;
for (; i < source.Count; i++)
{
if (!predicate(source[i])) {
break;
}
}
var result = new List<T>(source.Count - i);
for (; i < source.Count; i++)
{
result.Add(source[i]);
}
return result;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 0266806ba237aed45b52c7709de1fe6b
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,504 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- ARRAYS --------------------------------------------
/// <summary>
/// Adds a sequence of values.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <returns>The sum of the sequence.</returns>
public static int SumF(this int[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
int sum = 0;
checked
{
foreach (var v in source)
{
sum += v;
}
}
return sum;
}
/// <summary>
/// Adds the transformed sequence of elements.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static int SumF<T>(this T[] source, Func<T, int> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
int sum = 0;
checked
{
foreach (var v in source)
{
sum += selector(v);
}
}
return sum;
}
/// <summary>
/// Adds a sequence of values.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <returns>The sum of the sequence.</returns>
public static long SumF(this long[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
long sum = 0;
checked
{
foreach (var v in source)
{
sum += v;
}
}
return sum;
}
/// <summary>
/// Adds the transformed sequence of elements.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static long SumF<T>(this T[] source, Func<T, long> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
long sum = 0;
checked
{
foreach (var v in source)
{
sum += selector(v);
}
}
return sum;
}
/// <summary>
/// Adds a sequence of values.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <returns>The sum of the sequence.</returns>
public static float SumF(this float[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
double sum = 0;
foreach (var v in source)
{
sum += v;
}
return (float)sum;
}
/// <summary>
/// Adds the transformed sequence of elements.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static float SumF<T>(this T[] source, Func<T, float> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double sum = 0;
foreach (var v in source)
{
sum += selector(v);
}
return (float)sum;
}
/// <summary>
/// Adds a sequence of values.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <returns>The sum of the sequence.</returns>
public static double SumF(this double[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
double sum = 0;
foreach (var v in source)
{
sum += v;
}
return sum;
}
/// <summary>
/// Adds the transformed sequence of elements.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static double SumF<T>(this T[] source, Func<T, double> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double sum = 0;
foreach (var v in source)
{
sum += selector(v);
}
return sum;
}
/// <summary>
/// Adds a sequence of values.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <returns>The sum of the sequence.</returns>
public static decimal SumF(this decimal[] source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
decimal sum = 0;
foreach (var v in source)
{
sum += v;
}
return sum;
}
/// <summary>
/// Adds the transformed sequence of elements.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static decimal SumF<T>(this T[] source, Func<T, decimal> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
decimal sum = 0;
foreach (var v in source)
{
sum += selector(v);
}
return sum;
}
// -------------------------- LISTS --------------------------------------------
/// <summary>
/// Adds a sequence of values.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <returns>The sum of the sequence.</returns>
public static int SumF(this List<int> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
int sum = 0;
checked
{
for (int i = 0; i < source.Count; i++)
{
sum += source[i];
}
}
return sum;
}
/// <summary>
/// Adds the transformed sequence of elements.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static int SumF<T>(this List<T> source, Func<T, int> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
int sum = 0;
checked
{
for (int i = 0; i < source.Count; i++)
{
sum += selector(source[i]);
}
}
return sum;
}
/// <summary>
/// Adds a sequence of values.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <returns>The sum of the sequence.</returns>
public static long SumF(this List<long> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
long sum = 0;
checked
{
for (int i = 0; i < source.Count; i++)
{
sum += source[i];
}
}
return sum;
}
/// <summary>
/// Adds the transformed sequence of elements.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static long SumF<T>(this List<T> source, Func<T, long> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
long sum = 0;
checked
{
for (int i = 0; i < source.Count; i++)
{
sum += selector(source[i]);
}
}
return sum;
}
/// <summary>
/// Adds a sequence of values.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <returns>The sum of the sequence.</returns>
public static float SumF(this List<float> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
double sum = 0;
for (int i = 0; i < source.Count; i++)
{
sum += source[i];
}
return (float)sum;
}
/// <summary>
/// Adds the transformed sequence of elements.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static float SumF<T>(this List<T> source, Func<T, float> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double sum = 0;
for (int i = 0; i < source.Count; i++)
{
sum += selector(source[i]);
}
return (float)sum;
}
/// <summary>
/// Adds a sequence of values.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <returns>The sum of the sequence.</returns>
public static double SumF(this List<double> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
double sum = 0;
for (int i = 0; i < source.Count; i++)
{
sum += source[i];
}
return sum;
}
/// <summary>
/// Adds the transformed sequence of elements.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static double SumF<T>(this List<T> source, Func<T, double> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double sum = 0;
for (int i = 0; i < source.Count; i++)
{
sum += selector(source[i]);
}
return sum;
}
/// <summary>
/// Adds a sequence of values.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <returns>The sum of the sequence.</returns>
public static decimal SumF(this List<decimal> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
decimal sum = 0;
for (int i = 0; i < source.Count; i++)
{
sum += source[i];
}
return sum;
}
/// <summary>
/// Adds the transformed sequence of elements.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static decimal SumF<T>(this List<T> source, Func<T, decimal> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
decimal sum = 0;
for (int i = 0; i < source.Count; i++)
{
sum += selector(source[i]);
}
return sum;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: c45ad2500ea1ddd46af3645fba2bfc4c
timeCreated: 1518622477
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,188 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
/// <summary>
/// Returns a specified number of contiguous elements from the start of a sequence.
/// </summary>
/// <param name="source">The sequence to return elements from.</param>
/// <param name="count">The number of elements to return.</param>
/// <returns>A sequence that contains the specified number of elements from the start of the input sequence.</returns>
public static T[] TakeF<T>(this T[] source, int count)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (count < 0)
{
count = 0;
}
else if (count > source.Length)
{
count = source.Length;
}
var result = new T[count];
Array.Copy(source, 0, result, 0, count);
return result;
}
/// <summary>
/// Returns elements from a sequence as long as a specified condition is true.
/// </summary>
/// <param name="source">A sequence to return elements from.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>A sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.</returns>
public static T[] TakeWhileF<T>(this T[] source, Func<T, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var result = new List<T>();
for (int i = 0; i < source.Length; i++)
{
if (predicate(source[i]))
result.Add(source[i]);
else
return result.ToArray();
}
return result.ToArray();
}
/// <summary>
/// Returns elements from a sequence as long as a specified condition is true. The element's index is used in the logic of the predicate function.
/// </summary>
/// <param name="source">The sequence to return elements from.</param>
/// <param name="predicate">A function to test each source element for a condition; the second parameter of the function represents the index of the source element.</param>
/// <returns>A sequence that contains elements from the input sequence that occur before the element at which the test no longer passes.</returns>
public static T[] TakeWhileF<T>(this T[] source, Func<T,int, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var result = new List<T>();
for (int i = 0; i < source.Length; i++)
{
if (predicate(source[i],i))
result.Add(source[i]);
else
return result.ToArray();
}
return result.ToArray();
}
// ------------- Lists ----------------
/// <summary>
/// Returns a specified number of contiguous elements from the start of a sequence.
/// </summary>
/// <param name="source">The sequence to return elements from.</param>
/// <param name="count">The number of elements to return.</param>
/// <returns>A sequence that contains the specified number of elements from the start of the input sequence.</returns>
public static List<T> TakeF<T>(this List<T> source, int count)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (count < 0)
{
count = 0;
}
else if (count > source.Count)
{
count = source.Count;
}
var result = new List<T>(count);
for (int i = 0; i < count; i++)
{
result.Add(source[i]);
}
return result;
}
/// <summary>
/// Returns elements from a sequence as long as a specified condition is true.
/// </summary>
/// <param name="source">A sequence to return elements from.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>A sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.</returns>
public static List<T> TakeWhileF<T>(this List<T> source, Func<T, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var result = new List<T>();
for (int i = 0; i < source.Count; i++)
{
if (predicate(source[i]))
{
result.Add(source[i]);
}
else
{
return result;
}
}
return result;
}
/// <summary>
/// Returns elements from a sequence as long as a specified condition is true. The element's index is used in the logic of the predicate function.
/// </summary>
/// <param name="source">The sequence to return elements from.</param>
/// <param name="predicate">A function to test each source element for a condition; the second parameter of the function represents the index of the source element.</param>
/// <returns>A sequence that contains elements from the input sequence that occur before the element at which the test no longer passes.</returns>
public static List<T> TakeWhileF<T>(this List<T> source, Func<T, int, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var result = new List<T>();
for (int i = 0; i < source.Count; i++)
{
if (predicate(source[i], i))
result.Add(source[i]);
else
return result;
}
return result;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: f9aaaef92e9c332418190038d49b4389
timeCreated: 1518622478
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: d27acc7ea045f65488b96d108768512f
folderAsset: yes
timeCreated: 1518622476
licenseType: Free
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace JM.LinqFaster.Utils {
//Takes a comparer, and creates a reverse comparer, for Descending sorts
internal sealed class ComparerReverser<T> : IComparer<T> {
private readonly IComparer<T> wrappedComparer;
public ComparerReverser(IComparer<T> wrappedComparer) {
this.wrappedComparer = wrappedComparer;
}
#if !(UNITY_4 || UNITY_5)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public int Compare(T x, T y) {
return wrappedComparer.Compare(y, x);
}
}
internal static class ComparerExtensions {
// Lets us reverse a comparere with comparer.Reverse();
public static IComparer<T> Reverse<T>(this IComparer<T> comparer) {
return new ComparerReverser<T>(comparer);
}
}
internal sealed class LambdaComparer<T, U> : IComparer<T> {
IComparer<U> comparer;
Func<T, U> selector;
public LambdaComparer(Func<T, U> selector, IComparer<U> comparer) {
this.comparer = comparer;
this.selector = selector;
}
#if !(UNITY_4 || UNITY_5)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public int Compare(T x, T y) {
return comparer.Compare(selector(x), selector(y));
}
}
internal sealed class ReverseLambdaComparer<T, U> : IComparer<T> {
IComparer<U> comparer;
Func<T, U> selector;
public ReverseLambdaComparer(Func<T, U> selector, IComparer<U> comparer) {
this.comparer = comparer;
this.selector = selector;
}
#if !(UNITY_4 || UNITY_5)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public int Compare(T x, T y) {
return comparer.Compare(selector(y), selector(x));
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 58968b2b3f2b61943a1723873cdb7288
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,38 @@
#if !(UNITY_4 || UNITY_5)
using System;
using System.Collections.Concurrent;
namespace JM.LinqFaster.Utils
{
internal static class CustomPartition
{
public static OrderablePartitioner<Tuple<int,int>> MakePartition(int len, int? batchSize)
{
if (batchSize == null)
{
return Partitioner.Create(0, len);
}
else
{
return Partitioner.Create(0, len, batchSize.Value);
}
}
public static OrderablePartitioner<Tuple<int, int>> MakeSIMDPartition(int len, int chunkSize, int? batchSize)
{
int chunkLen = len - len % chunkSize;
int numChunks = chunkLen / chunkSize;
if (batchSize == null)
{
return Partitioner.Create(0, numChunks,numChunks/Environment.ProcessorCount);
}
else
{
return Partitioner.Create(0, numChunks, batchSize.Value);
}
}
}
}
#endif

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 117a499c9c8ce1a47a30c4cb3de95a14
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,18 @@
using System;
internal static class Error
{
internal static Exception ArgumentNull(string s) { return new ArgumentNullException(s); }
internal static Exception ArgumentOutOfRange(string s) { return new ArgumentOutOfRangeException(s); }
internal static Exception MoreThanOneElement() { return new InvalidOperationException("Sequence contains more than one element"); }
internal static Exception MoreThanOneMatch() { return new InvalidOperationException("Sequence contains more than one matching element"); }
internal static Exception NoElements() { return new InvalidOperationException("Sequence contains no elements"); }
internal static Exception NoMatch() { return new InvalidOperationException("Sequence contains no matching element"); }
internal static Exception NotSupported() { return new NotSupportedException(); }
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 2f77eee1e24f34f438756aca3d8506d9
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,323 @@
#if !(UNITY_4 || UNITY_5)
using System;
using System.Runtime.CompilerServices;
/*
C# has no way to constrain a generic to only primitive types.
You can only constrain them to value types via:
where T : struct
All primitives are value types but not all value types are
primitives. Thus, when you try to do operations like + > < ==
on generic value types, you get a compiler error. These methods
work around that by checking the type, casting, and performing the
operation. The JIT elides all of the non relevant bits of the If statement
for each generic type, so this is remarkably still fast. Since these are
only used for the SIMD specific operations, and the SIMD library
works exactly this way as well, it does not add any problems that
don't already exist when you use .NET SIMD. Which is, if you create a
Vector<T> where T is a non primitive value type, you will get a runtime error.
*/
namespace JM.LinqFaster.Utils
{
internal static class GenericOperators
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T Add<T>(T a, T b)
{
if (typeof(T) == typeof(Byte))
{
return (T)(object)((Byte)(object)a + (Byte)(object)b);
}
else if (typeof(T) == typeof(SByte))
{
return (T)(object)((SByte)(object)a + (SByte)(object)b);
}
else if (typeof(T) == typeof(UInt16))
{
return (T)(object)((UInt16)(object)a + (UInt16)(object)b);
}
else if (typeof(T) == typeof(Int16))
{
return (T)(object)((Int16)(object)a + (Int16)(object)b);
}
else if (typeof(T) == typeof(UInt32))
{
return (T)(object)((UInt32)(object)a + (UInt32)(object)b);
}
else if (typeof(T) == typeof(Int32))
{
return (T)(object)((Int32)(object)a + (Int32)(object)b);
}
else if (typeof(T) == typeof(UInt64))
{
return (T)(object)((UInt64)(object)a + (UInt64)(object)b);
}
else if (typeof(T) == typeof(Int64))
{
return (T)(object)((Int64)(object)a + (Int64)(object)b);
}
else if (typeof(T) == typeof(Single))
{
return (T)(object)((Single)(object)a + (Single)(object)b);
}
else if (typeof(T) == typeof(Double))
{
return (T)(object)((Double)(object)a + (Double)(object)b);
}
else
{
throw new NotSupportedException("Nope");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool GreaterThan<T>(T a, T b)
{
if (typeof(T) == typeof(Byte))
{
return ((Byte)(object)a > (Byte)(object)b);
}
else if (typeof(T) == typeof(SByte))
{
return ((SByte)(object)a > (SByte)(object)b);
}
else if (typeof(T) == typeof(UInt16))
{
return ((UInt16)(object)a > (UInt16)(object)b);
}
else if (typeof(T) == typeof(Int16))
{
return ((Int16)(object)a > (Int16)(object)b);
}
else if (typeof(T) == typeof(UInt32))
{
return ((UInt32)(object)a > (UInt32)(object)b);
}
else if (typeof(T) == typeof(Int32))
{
return ((Int32)(object)a > (Int32)(object)b);
}
else if (typeof(T) == typeof(UInt64))
{
return ((UInt64)(object)a > (UInt64)(object)b);
}
else if (typeof(T) == typeof(Int64))
{
return ((Int64)(object)a > (Int64)(object)b);
}
else if (typeof(T) == typeof(Single))
{
return ((Single)(object)a > (Single)(object)b);
}
else if (typeof(T) == typeof(Double))
{
return ((Double)(object)a > (Double)(object)b);
}
else
{
throw new NotSupportedException("Nope");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool Equals<T>(T a, T b)
{
if (typeof(T) == typeof(Byte))
{
return ((Byte)(object)a == (Byte)(object)b);
}
else if (typeof(T) == typeof(SByte))
{
return ((SByte)(object)a == (SByte)(object)b);
}
else if (typeof(T) == typeof(UInt16))
{
return ((UInt16)(object)a == (UInt16)(object)b);
}
else if (typeof(T) == typeof(Int16))
{
return ((Int16)(object)a == (Int16)(object)b);
}
else if (typeof(T) == typeof(UInt32))
{
return ((UInt32)(object)a == (UInt32)(object)b);
}
else if (typeof(T) == typeof(Int32))
{
return ((Int32)(object)a == (Int32)(object)b);
}
else if (typeof(T) == typeof(UInt64))
{
return ((UInt64)(object)a == (UInt64)(object)b);
}
else if (typeof(T) == typeof(Int64))
{
return ((Int64)(object)a == (Int64)(object)b);
}
else if (typeof(T) == typeof(Single))
{
return ((Single)(object)a == (Single)(object)b);
}
else if (typeof(T) == typeof(Double))
{
return ((Double)(object)a == (Double)(object)b);
}
else
{
throw new NotSupportedException("Nope");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool LessThan<T>(T a, T b)
{
if (typeof(T) == typeof(Byte))
{
return ((Byte)(object)a < (Byte)(object)b);
}
else if (typeof(T) == typeof(SByte))
{
return ((SByte)(object)a < (SByte)(object)b);
}
else if (typeof(T) == typeof(UInt16))
{
return ((UInt16)(object)a < (UInt16)(object)b);
}
else if (typeof(T) == typeof(Int16))
{
return ((Int16)(object)a < (Int16)(object)b);
}
else if (typeof(T) == typeof(UInt32))
{
return ((UInt32)(object)a < (UInt32)(object)b);
}
else if (typeof(T) == typeof(Int32))
{
return ((Int32)(object)a < (Int32)(object)b);
}
else if (typeof(T) == typeof(UInt64))
{
return ((UInt64)(object)a < (UInt64)(object)b);
}
else if (typeof(T) == typeof(Int64))
{
return ((Int64)(object)a < (Int64)(object)b);
}
else if (typeof(T) == typeof(Single))
{
return ((Single)(object)a < (Single)(object)b);
}
else if (typeof(T) == typeof(Double))
{
return ((Double)(object)a < (Double)(object)b);
}
else
{
throw new NotSupportedException("Nope");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Divide<T>(T a, double b)
{
if (typeof(T) == typeof(Byte))
{
return (double)(object)((Byte)(object)a /b) ;
}
else if (typeof(T) == typeof(SByte))
{
return (double)(object)((SByte)(object)a /b);
}
else if (typeof(T) == typeof(UInt16))
{
return (double)(object)((UInt16)(object)a / b);
}
else if (typeof(T) == typeof(Int16))
{
return (double)(object)((Int16)(object)a / b);
}
else if (typeof(T) == typeof(UInt32))
{
return (double)(object)((UInt32)(object)a / b);
}
else if (typeof(T) == typeof(Int32))
{
return (double)(object)((Int32)(object)a /b);
}
else if (typeof(T) == typeof(UInt64))
{
return (double)(object)((UInt64)(object)a / b);
}
else if (typeof(T) == typeof(Int64))
{
return (double)(object)((Int64)(object)a /b);
}
else if (typeof(T) == typeof(Single))
{
return (double)(object)((Single)(object)a /b);
}
else if (typeof(T) == typeof(Double))
{
return (double)(object)((Double)(object)a / b);
}
else
{
throw new NotSupportedException("Nope");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float DivideFloat<T>(T a, float b)
{
if (typeof(T) == typeof(Byte))
{
return (float)(object)((Byte)(object)a / b);
}
else if (typeof(T) == typeof(SByte))
{
return (float)(object)((SByte)(object)a / b);
}
else if (typeof(T) == typeof(UInt16))
{
return (float)(object)((UInt16)(object)a / b);
}
else if (typeof(T) == typeof(Int16))
{
return (float)(object)((Int16)(object)a / b);
}
else if (typeof(T) == typeof(UInt32))
{
return (float)(object)((UInt32)(object)a / b);
}
else if (typeof(T) == typeof(Int32))
{
return (float)(object)((Int32)(object)a / b);
}
else if (typeof(T) == typeof(UInt64))
{
return (float)(object)((UInt64)(object)a / b);
}
else if (typeof(T) == typeof(Int64))
{
return (float)(object)((Int64)(object)a / b);
}
else if (typeof(T) == typeof(Single))
{
return (float)(object)((Single)(object)a / b);
}
else if (typeof(T) == typeof(Double))
{
return (float)(object)((Double)(object)a / b);
}
else
{
throw new NotSupportedException("Nope");
}
}
}
}
#endif

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: c55248b8089617346a6a1b22dc43009f
timeCreated: 1518622478
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,127 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- ARRAYS --------------------------------------------
/// <summary>
/// Filters a sequence of values based on a predicate.
/// </summary>
/// <param name="source">A sequence to filter.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>A sequence that contains elements from the input sequence that satisfy the condition.</returns>
public static T[] WhereF<T>(this T[] source, Func<T, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
T[] result = new T[source.Length];
int idx = 0;
for (int i = 0; i < source.Length; i++)
{
if (predicate(source[i]))
{
result[idx] = source[i];
idx++;
}
}
Array.Resize(ref result, idx);
return result;
}
/// <summary>
/// Filters a sequence of values based on a predicate that includes the index in it's logic.
/// </summary>
/// <param name="source">A sequence to filter.</param>
/// <param name="predicate">A function to test each element for a condition along with the element's index.</param>
/// <returns>A sequence that contains elements from the input sequence that satisfy the condition.</returns>
public static T[] WhereF<T>(this T[] source, Func<T, int, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
T[] result = new T[source.Length];
int idx = 0;
for (int i = 0; i < source.Length; i++)
{
if (predicate(source[i], i))
{
result[idx] = source[i];
idx++;
}
}
Array.Resize(ref result, idx);
return result;
}
// -------------------------- LISTS --------------------------------------------
/// <summary>
/// Filters a sequence of values based on a predicate.
/// </summary>
/// <param name="source">A sequence to filter.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>A sequence that contains elements from the input sequence that satisfy the condition.</returns>
public static List<T> WhereF<T>(this List<T> source, Predicate<T> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
return source.FindAll(predicate);
}
/// <summary>
/// Filters a sequence of values based on a predicate that includes the index in it's logic.
/// </summary>
/// <param name="source">A sequence to filter.</param>
/// <param name="predicate">A function to test each element for a condition along with the element's index.</param>
/// <returns>A sequence that contains elements from the input sequence that satisfy the condition.</returns>
public static List<T> WhereF<T>(this List<T> source, Func<T, int, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
List<T> r = new List<T>();
for (int i = 0; i < source.Count; i++)
{
if (predicate(source[i], i)) r.Add(source[i]);
}
return r;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 089655aa3554c044c827c1c259eb1e00
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,335 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// ----------------------------- Arrays ------------------
/// <summary>
/// Combines Where and Aggregate for optimal performance
/// </summary>
/// <param name="source">The input to filter then aggregate.</param>
/// <param name="predicate">The function to filter the input sequence with.</param>
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
/// <returns>The filtered then aggregated sequence.</returns>
public static T WhereAggregateF<T>(this T[] source, Func<T, bool> predicate, Func<T, T, T> func)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
if (func == null)
{
throw Error.ArgumentNull("func");
}
var result = default(T);
int i = 0;
for (; i < source.Length; i++)
{
if (predicate(source[i]))
{
result = source[i];
i++;
break;
}
}
for (; i < source.Length; i++)
{
if (predicate(source[i]))
{
result = func(result, source[i]);
}
}
return result;
}
/// <summary>
/// Combines Where and Aggregate with index for optimal performance
/// </summary>
/// <param name="source">The input to filter then aggregate.</param>
/// <param name="predicate">The function to filter the input sequence and it's index with.</param>
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
/// <returns>The filtered then aggregated sequence.</returns>
public static T WhereAggregateF<T>(this T[] source, Func<T, int, bool> predicate, Func<T, T,T> func)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var result = default(T);
int i = 0;
for (; i < source.Length; i++)
{
if (predicate(source[i], i))
{
result = source[i];
i++;
break;
}
}
for (; i < source.Length; i++)
{
if (predicate(source[i], i))
{
result = func(result, source[i]);
}
}
return result;
}
/// <summary>
/// Combines Where and Aggregate for optimal performance with a starting seed.
/// </summary>
/// <param name="source">The input to filter then aggregate.</param>
/// <param name="predicate">The function to filter the input sequence with.</param>
/// <param name="seed">The initial value to aggregate on.</param>
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
/// <returns>The filtered then aggregated sequence.</returns>
public static TAccumulate WhereAggregateF<TSource, TAccumulate>(this TSource[] source, Func<TSource, bool> predicate, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (func == null)
{
throw Error.ArgumentNull("func");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
TAccumulate result = seed;
foreach (var v in source)
{
if (predicate(v))
result = func(result, v);
}
return result;
}
/// <summary>
/// Combines Where and Aggregate for optimal performance with a starting seed and a result transformation.
/// </summary>
/// <param name="source">The input to filter then aggregate.</param>
/// <param name="predicate">The function to filter the input sequence with.</param>
/// <param name="seed">The initial value to aggregate on.</param>
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
/// <param name="resultSelector">A function to transform the final result.</param>
/// <returns>The filtered then aggregated then transformed sequence.</returns>
public static TResult WhereAggregateF<TSource, TAccumulate, TResult>(this TSource[] source, Func<TSource, bool> predicate, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (func == null)
{
throw Error.ArgumentNull("func");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
if (resultSelector == null)
{
throw Error.ArgumentNull("resultSelector");
}
TAccumulate result = seed;
int count = 0;
foreach (var v in source)
{
if (predicate(v)) {
result = func(result, v);
count++;
}
}
return resultSelector(result);
}
// --------------------------- Lists -------------------------
/// <summary>
/// Combines Where and Aggregate for optimal performance
/// </summary>
/// <param name="source">The input to filter then aggregate.</param>
/// <param name="predicate">The function to filter the input sequence with.</param>
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
/// <returns>The filtered then aggregated sequence.</returns>
public static T WhereAggregateF<T>(this List<T> source, Func<T, bool> predicate, Func<T, T, T> func)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
if (func == null)
{
throw Error.ArgumentNull("func");
}
var result = default(T);
int i = 0;
for (; i < source.Count; i++)
{
if (predicate(source[i]))
{
result = source[i];
i++;
break;
}
}
for (; i < source.Count; i++)
{
if (predicate(source[i]))
{
result = func(result, source[i]);
}
}
return result;
}
/// <summary>
/// Combines Where and Aggregate with index for optimal performance
/// </summary>
/// <param name="source">The input to filter then aggregate.</param>
/// <param name="predicate">The function to filter the input sequence and it's index with.</param>
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
/// <returns>The filtered then aggregated sequence.</returns>
public static T WhereAggregateF<T>(this List<T> source, Func<T, int, bool> predicate, Func<T, T, T> func)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
var result = default(T);
int i = 0;
for (; i < source.Count; i++)
{
if (predicate(source[i], i))
{
result = source[i];
i++;
break;
}
}
for (; i < source.Count; i++)
{
if (predicate(source[i], i))
{
result = func(result, source[i]);
}
}
return result;
}
/// <summary>
/// Combines Where and Aggregate for optimal performance with a starting seed.
/// </summary>
/// <param name="source">The input to filter then aggregate.</param>
/// <param name="predicate">The function to filter the input sequence with.</param>
/// <param name="seed">The initial value to aggregate on.</param>
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
/// <returns>The filtered then aggregated sequence.</returns>
public static TAccumulate WhereAggregateF<TSource, TAccumulate>(this List<TSource> source, Func<TSource, bool> predicate, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (func == null)
{
throw Error.ArgumentNull("func");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
TAccumulate result = seed;
for (int i = 0; i < source.Count; i++)
{
var v = source[i];
if (predicate(v))
result = func(result, v);
}
return result;
}
/// <summary>
/// Combines Where and Aggregate for optimal performance with a starting seed and a result transformation.
/// </summary>
/// <param name="source">The input to filter then aggregate.</param>
/// <param name="predicate">The function to filter the input sequence with.</param>
/// <param name="seed">The initial value to aggregate on.</param>
/// <param name="func">The function to aggregate the filtered seqeuence.</param>
/// <param name="resultSelector">A function to transform the final result.</param>
/// <returns>The filtered then aggregated then transformed sequence.</returns>
public static TResult WhereAggregateF<TSource, TAccumulate, TResult>(this List<TSource> source, Func<TSource, bool> predicate, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (func == null)
{
throw Error.ArgumentNull("func");
}
if (resultSelector == null)
{
throw Error.ArgumentNull("resultSelector");
}
TAccumulate result = seed;
for (int i = 0; i < source.Count; i++)
{
var v = source[i];
if (predicate(v))
result = func(result, v);
}
return resultSelector(result);
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: ba74d3462bb50a647b34d3988b598cda
timeCreated: 1518622477
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,164 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- ARRAYS --------------------------------------------
/// <summary>
/// Combined Where and Select for optimal performance.
/// </summary>
/// <param name="source">The input sequence to filter then transform.</param>
/// <param name="predicate">A function to use to filter the sequence.</param>
/// <param name="selector">A function to transform the filtered elements.</param>
/// <returns>A sequence of filtered and transformed elements.</returns>
public static TResult[] WhereSelectF<T, TResult>(this T[] source, Func<T, bool> predicate, Func<T, TResult> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
if (selector == null)
{
throw Error.ArgumentNull("predicate");
}
var result = new TResult[source.Length];
int idx = 0;
for (int i = 0; i < source.Length; i++)
{
if (predicate(source[i]))
{
result[idx] = selector(source[i]);
idx++;
}
}
Array.Resize(ref result, idx);
return result;
}
/// <summary>
/// Combined Where and Select for optimal performance that uses the index in the
/// predicate and selector.
/// </summary>
/// <param name="source">The input sequence to filter then transform.</param>
/// <param name="predicate">A function to use to filter the sequence.</param>
/// <param name="selector">A function to transform the filtered elements.</param>
/// <returns>A sequence of filtered and transformed elements.</returns>
public static TResult[] WhereSelectF<T, TResult>(this T[] source, Func<T, int, bool> predicate, Func<T, int, TResult> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
if (selector == null)
{
throw Error.ArgumentNull("predicate");
}
var result = new TResult[source.Length];
int idx = 0;
for (int i = 0; i < source.Length; i++)
{
if (predicate(source[i], i))
{
result[idx] = selector(source[i], idx);
idx++;
}
}
Array.Resize(ref result, idx);
return result;
}
// -------------------------- LISTS --------------------------------------------
/// <summary>
/// Combined Where and Select for optimal performance.
/// </summary>
/// <param name="source">The input sequence to filter then transform.</param>
/// <param name="predicate">A function to use to filter the sequence.</param>
/// <param name="selector">A function to transform the filtered elements.</param>
/// <returns>A sequence of filtered and transformed elements.</returns>
public static List<TResult> WhereSelectF<T, TResult>(this List<T> source, Func<T, bool> predicate, Func<T, TResult> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
if (selector == null)
{
throw Error.ArgumentNull("predicate");
}
var r = new List<TResult>();
for (int i = 0; i < source.Count; i++)
{
if (predicate(source[i])) r.Add(selector(source[i]));
}
return r;
}
/// <summary>
/// Combined Where and Select for optimal performance that uses the index in the
/// predicate and selector.
/// </summary>
/// <param name="source">The input sequence to filter then transform.</param>
/// <param name="predicate">A function to use to filter the sequence.</param>
/// <param name="selector">A function to transform the filtered elements.</param>
/// <returns>A sequence of filtered and transformed elements.</returns>
public static List<TResult> WhereSelectF<T, TResult>(this List<T> source, Func<T, int, bool> predicate, Func<T, int, TResult> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
if (selector == null)
{
throw Error.ArgumentNull("predicate");
}
var r = new List<TResult>();
int idx = 0;
for (int i = 0; i < source.Count; i++)
{
if (predicate(source[i], i)) {
r.Add(selector(source[i], idx));
idx++;
}
}
return r;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 20a5c369792516b4f8326236fc378f5c
timeCreated: 1518622476
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,594 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- ARRAYS --------------------------------------------
/// <summary>
/// Adds the values in the sequence that match the where predicate.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <returns>The sum of the sequence.</returns>
public static int WhereSumF(this int[] source, Func<int,bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
int sum = 0;
checked
{
foreach (var v in source)
{
if (predicate(v))
{
sum += v;
}
}
}
return sum;
}
/// <summary>
/// Performs a filter with the where predicate, then sums the transformed values.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static int WhereSumF<T>(this T[] source,Func<T,bool> predicate, Func<T, int> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
int sum = 0;
checked
{
foreach (var v in source)
{
if (predicate(v))
{
sum += selector(v);
}
}
}
return sum;
}
/// <summary>
/// Adds the values in the sequence that match the where predicate.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <returns>The sum of the sequence.</returns>
public static long WhereSumF(this long[] source,Func<long,bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
long sum = 0;
checked
{
foreach (var v in source)
{
if (predicate(v))
{
sum += v;
}
}
}
return sum;
}
/// <summary>
/// Performs a filter with the where predicate, then sums the transformed values.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static long WhereSumF<T>(this T[] source,Func<T,bool> predicate, Func<T, long> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
long sum = 0;
checked
{
foreach (var v in source)
{
if (predicate(v))
{
sum += selector(v);
}
}
}
return sum;
}
/// <summary>
/// Adds the values in the sequence that match the where predicate.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <returns>The sum of the sequence.</returns>
public static float WhereSumF(this float[] source, Func<float,bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
double sum = 0;
foreach (var v in source)
{
if (predicate(v))
{
sum += v;
}
}
return (float)sum;
}
/// <summary>
/// Performs a filter with the where predicate, then sums the transformed values.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static float WhereSumF<T>(this T[] source, Func<T,bool> predicate,Func<T, float> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double sum = 0;
foreach (var v in source)
{
if (predicate(v))
{
sum += selector(v);
}
}
return (float)sum;
}
/// <summary>
/// Adds the values in the sequence that match the where predicate.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <returns>The sum of the sequence.</returns>
public static double WhereSumF(this double[] source, Func<double,bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
double sum = 0;
foreach (var v in source)
{
if (predicate(v))
{
sum += v;
}
}
return sum;
}
/// <summary>
/// Performs a filter with the where predicate, then sums the transformed values.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static double WhereSumF<T>(this T[] source, Func<T,bool> predicate,Func<T, double> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double sum = 0;
foreach (var v in source)
{
if (predicate(v))
{
sum += selector(v);
}
}
return sum;
}
/// <summary>
/// Adds the values in the sequence that match the where predicate.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <returns>The sum of the sequence.</returns>
public static decimal WhereSumF(this decimal[] source, Func<decimal,bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
decimal sum = 0;
foreach (var v in source)
{
if (predicate(v))
{
sum += v;
}
}
return sum;
}
/// <summary>
/// Performs a filter with the where predicate, then sums the transformed values.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static decimal WhereSumF<T>(this T[] source,Func<T,bool> predicate, Func<T, decimal> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
decimal sum = 0;
foreach (var v in source)
{
if (predicate(v))
{
sum += selector(v);
}
}
return sum;
}
// -------------------------- LISTS --------------------------------------------
/// <summary>
/// Adds the values in the sequence that match the where predicate.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <returns>The sum of the sequence.</returns>
public static int WhereSumF(this List<int> source, Func<int,bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
int sum = 0;
checked
{
for (int i = 0; i < source.Count; i++)
{
var s = source[i];
if (predicate(s))
{
sum += s;
}
}
}
return sum;
}
/// <summary>
/// Performs a filter with the where predicate, then sums the transformed values.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static int WhereSumF<T>(this List<T> source, Func<T,bool> predicate, Func<T, int> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
int sum = 0;
checked
{
for (int i = 0; i < source.Count; i++)
{
var s = source[i];
if (predicate(s))
{
sum += selector(s);
}
}
}
return sum;
}
/// <summary>
/// Adds the values in the sequence that match the where predicate.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <returns>The sum of the sequence.</returns>
public static long WhereSumF(this List<long> source, Func<long,bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
long sum = 0;
checked
{
for (int i = 0; i < source.Count; i++)
{
var s = source[i];
if (predicate(s))
{
sum += s;
}
}
}
return sum;
}
/// <summary>
/// Performs a filter with the where predicate, then sums the transformed values.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static long WhereSumF<T>(this List<T> source, Func<T,bool> predicate, Func<T, long> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
long sum = 0;
checked
{
for (int i = 0; i < source.Count; i++)
{
var s = source[i];
if (predicate(s))
{
sum += selector(s);
}
}
}
return sum;
}
/// <summary>
/// Adds the values in the sequence that match the where predicate.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <returns>The sum of the sequence.</returns>
public static float WhereSumF(this List<float> source, Func<float,bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
double sum = 0;
for (int i = 0; i < source.Count; i++)
{
var s = source[i];
if (predicate(s))
{
sum += s;
}
}
return (float)sum;
}
/// <summary>
/// Performs a filter with the where predicate, then sums the transformed values.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static float WhereSumF<T>(this List<T> source, Func<T,bool> predicate,Func<T, float> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double sum = 0;
for (int i = 0; i < source.Count; i++)
{
var s = source[i];
if (predicate(s))
{
sum += selector(s);
}
}
return (float)sum;
}
/// <summary>
/// Adds the values in the sequence that match the where predicate.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <returns>The sum of the sequence.</returns>
public static double WhereSumF(this List<double> source, Func<double,bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
double sum = 0;
for (int i = 0; i < source.Count; i++)
{
var s = source[i];
if (predicate(s))
{
sum += s;
}
}
return sum;
}
/// <summary>
/// Performs a filter with the where predicate, then sums the transformed values.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static double WhereSumF<T>(this List<T> source,Func<T,bool> predicate, Func<T, double> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
double sum = 0;
for (int i = 0; i < source.Count; i++)
{
var s = source[i];
if (predicate(s))
{
sum += selector(s);
}
}
return sum;
}
/// <summary>
/// Adds the values in the sequence that match the where predicate.
/// </summary>
/// <param name="source">The sequence to add.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <returns>The sum of the sequence.</returns>
public static decimal WhereSumF(this List<decimal> source, Func<decimal,bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
decimal sum = 0;
for (int i = 0; i < source.Count; i++)
{
var s = source[i];
if (predicate(s))
{
sum += s;
}
}
return sum;
}
/// <summary>
/// Performs a filter with the where predicate, then sums the transformed values.
/// </summary>
/// <param name="source">The sequence of values to transform then sum.</param>
/// <param name="predicate">A function to filter the sequence with before summing.</param>
/// <param name="selector">A transformation function.</param>
/// <returns>The sum of the transformed elements.</returns>
public static decimal WhereSumF<T>(this List<T> source, Func<T,bool> predicate,Func<T, decimal> selector)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
decimal sum = 0;
for (int i = 0; i < source.Count; i++)
{
var s = source[i];
if (predicate(s))
{
sum += selector(s);
}
}
return sum;
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: dcc2e4320bd136e4aaecbc9978013e58
timeCreated: 1518622478
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
/// <summary>
/// Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.
/// </summary>
/// <param name="first">The first sequence to merge.</param>
/// <param name="second">The second sequence to merge.</param>
/// <param name="selector">A function that specifies how to merge the elements from the two sequences.</param>
/// <returns>A sequence that contains merged elements of two input sequences.</returns>
public static R[] ZipF<T, U, R>(this T[] first, U[] second, Func<T, U, R> selector)
{
if (first == null)
{
throw Error.ArgumentNull("first");
}
if (second == null)
{
throw Error.ArgumentNull("second");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
//maintain array bounds elision
if (first.Length < second.Length)
{
var result = new R[first.Length];
for (int i = 0; i < first.Length; i++)
{
result[i] = selector(first[i], second[i]);
}
return result;
}
else
{
var result = new R[second.Length];
for (int i = 0; i < second.Length; i++)
{
result[i] = selector(first[i], second[i]);
}
return result;
}
}
/// <summary>
/// Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.
/// </summary>
/// <param name="first">The first sequence to merge.</param>
/// <param name="second">The second sequence to merge.</param>
/// <param name="selector">A function that specifies how to merge the elements from the two sequences.</param>
/// <returns>A sequence that contains merged elements of two input sequences.</returns>
public static List<R> ZipF<T, U, R>(this List<T> first, List<U> second, Func<T, U, R> selector)
{
if (first == null)
{
throw Error.ArgumentNull("first");
}
if (second == null)
{
throw Error.ArgumentNull("second");
}
if (selector == null)
{
throw Error.ArgumentNull("selector");
}
//maintain array bounds elision
if (first.Count < second.Count)
{
var result = new List<R>(first.Count);
for (int i = 0; i < first.Count; i++)
{
result.Add(selector(first[i], second[i]));
}
return result;
}
else
{
var result = new List<R>(second.Count);
for (int i = 0; i < second.Count; i++)
{
result.Add(selector(first[i], second[i]));
}
return result;
}
}
}
}

View file

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: d5cec6dd8a8dd0b4ab39e3fd25d1fa7b
timeCreated: 1518622478
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,68 @@
LinqFaster
Usage Guide
--------------------------------------------------------------------------
LinqFaster provides specialized versions of the Linq extensions methods
optimized for working with arrays and lists. LinqFaster methods use the
same names as Linq, but with an F (for Fast) appended to them so that
you can use LinqFaster alongside regular Linq. The semantics are identical
except for OrderBy which does not do a stable sort like Linq does.
Examples
--------------------------------------------------------------------------
//Create an array of with values -500 to 500
var myArray = LinqFaster.RangeArrayF(-500, 500);
//Create a List<T> with 1000 elements all set to 5.0
var myList = LinqFaster.RepeatListF(5.0, 1000);
//Compute sum, average, max,min
var sum = myArray.SumF();
var average = myArray.AverageF();
var min = myArray.Min();
var max = myArray.Max();
//As above but on a transformation
var sum2 = myArray.SumF(x => x*x);
var average2 = myArray.AverageF(x => x*x);
var min2 = myArray.Min(x => x*x);
var max2 = myArray.Max(x => x*x);
//Do a where and a select or select and where in a single pass
var newArray = myArray.WhereSelectF(x => x % 2 == 0,x=>x*x);
var newArray2 = myArray.SelectWhereF(x => x * x,x => x % 2 == 0);
//Compute the sum of only the even values in a single pass
var filteredSum = myArray.WhereAggregateF(x => x % 2 == 0, (acc, x) => acc + x);
//New in-place methods are provided where appropriate
myArray.SelectInPlace(x => x * x);
myArray.ReverseInPlace();
Limitations
--------------------------------------------------------------------------
These are purely imperative implementations of the same higher order
functions that Linq provides, but unlike Linq they are not lazily evaluated.
This means that when chaining functions together such as:
var a = data.Where(predicate).Select(transform).Aggregate(foo);
// or
var b = data.Select(selector).Sum();
Linq would not do any work until the calls to Sum() or Aggregate(), and thus
iterate over the collection only once and allocate very little. LinqFaster
used this way would iterate over the collection each time and allocate much
more. Sometimes the net result will still be faster overall but the better
approach is to use the combined LinqFaster operations such as
SelectWhere, WhereSelect, and WhereAggregate. For example the expressions
above would become:
var a = data.WhereAggregate(predicate,transform,foo);
// and
var b = data.Sum(selector);
This gets you the best of both worlds. The speed of memory locality and no
allocations at all. In short, think about how you are transforming your
data. In some cases normal Linq may be the better choice.

View file

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: b03cc13e7e812ab47b88f91d54b43c4d
timeCreated: 1518622496
licenseType: Free
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -7,18 +7,21 @@ using float2 = Unity.Mathematics.float2;
public class OrbitalEntity : Entity
{
private Guid _orbitData;
public Guid OrbitData;
public OrbitalEntity(GameContext context, Guid hull, IEnumerable<Guid> items, IEnumerable<Guid> cargo, Guid orbit, Guid zone) : base(context, hull, items, cargo, zone)
{
_orbitData = orbit;
OrbitData = orbit;
}
public override void Update(float delta)
{
var newPosition = Context.GetOrbitPosition(_orbitData);
Velocity = (newPosition - Position) / delta;
Position = newPosition;
if (OrbitData != Guid.Empty)
{
Velocity = Context.GetOrbitVelocity(OrbitData);
Position = Context.GetOrbitPosition(OrbitData);
}
base.Update(delta);
}
}

View file

@ -123,7 +123,7 @@ public class OrbitData : DatabaseEntry
public static float2 Evaluate(float phase)
{
phase *= (PI * 2);
phase *= PI * 2;
return new float2(sin(phase), cos(phase));
}
}

View file

@ -274,7 +274,7 @@ public class Planet
ChildDistanceMaximum = (i % 2 == 0 ? p0ChildDist : p1ChildDist)
};
child.ChildDistanceMinimum = Context.GlobalData.PlanetRadius(child.Mass) * 2;
child.Period = pow(child.Distance, Context.GlobalData.OrbitPeriodExponent) * Context.GlobalData.OrbitPeriodMultiplier;
child.Period = Context.OrbitalPeriod(child.Distance);
Children.Add(child);
}
@ -335,7 +335,7 @@ public class Planet
Distance = distances[i],
Phase = Context.Random.NextFloat()
};
child.Period = pow(child.Distance, Context.GlobalData.OrbitPeriodExponent) * Context.GlobalData.OrbitPeriodMultiplier;
child.Period = Context.OrbitalPeriod(child.Distance);
child.ChildDistanceMinimum = Context.GlobalData.PlanetRadius(child.Mass) * 2;
// Maximum child distance of child is the smallest distance to either of its neighbors
child.ChildDistanceMaximum = min(i == 0 ? child.Distance - ChildDistanceMinimum : child.Distance - distances[i - 1],