Fix RCS1077

This commit is contained in:
RoosterDragon
2023-03-18 12:47:08 +00:00
committed by Gustas
parent 499efa1d0a
commit 330ca92045
60 changed files with 110 additions and 97 deletions

View File

@@ -1023,6 +1023,9 @@ dotnet_diagnostic.RCS1072.severity = warning
# Remove redundant constructor. # Remove redundant constructor.
dotnet_diagnostic.RCS1074.severity = warning dotnet_diagnostic.RCS1074.severity = warning
# Optimize LINQ method call.
dotnet_diagnostic.RCS1077.severity = warning
# Use 'Count' property instead of 'Any' method. # Use 'Count' property instead of 'Any' method.
dotnet_diagnostic.RCS1080.severity = warning dotnet_diagnostic.RCS1080.severity = warning

View File

@@ -328,7 +328,7 @@ namespace OpenRA.FileSystem
if (name == ".") if (name == ".")
continue; continue;
resolved = Directory.GetFileSystemEntries(resolved).FirstOrDefault(e => e.Equals(Path.Combine(resolved, name), StringComparison.InvariantCultureIgnoreCase)); resolved = Array.Find(Directory.GetFileSystemEntries(resolved), e => e.Equals(Path.Combine(resolved, name), StringComparison.InvariantCultureIgnoreCase));
if (resolved == null) if (resolved == null)
return null; return null;

View File

@@ -162,7 +162,7 @@ namespace OpenRA
throw new YamlException(exceptionString); throw new YamlException(exceptionString);
} }
constructOrderCache = resolved.Select(r => r.Trait).ToList(); constructOrderCache = resolved.ConvertAll(r => r.Trait);
return constructOrderCache; return constructOrderCache;
} }

View File

@@ -670,7 +670,7 @@ namespace OpenRA
public MiniYamlBuilder(string value, List<MiniYamlNode> nodes) public MiniYamlBuilder(string value, List<MiniYamlNode> nodes)
{ {
Value = value; Value = value;
Nodes = nodes == null ? new List<MiniYamlNodeBuilder>() : nodes.Select(x => new MiniYamlNodeBuilder(x)).ToList(); Nodes = nodes == null ? new List<MiniYamlNodeBuilder>() : nodes.ConvertAll(x => new MiniYamlNodeBuilder(x));
} }
public MiniYaml Build() public MiniYaml Build()

View File

@@ -9,6 +9,7 @@
*/ */
#endregion #endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using OpenRA.Server; using OpenRA.Server;
@@ -42,7 +43,7 @@ namespace OpenRA.Network
static Player FindPlayerByClient(this World world, Session.Client c) static Player FindPlayerByClient(this World world, Session.Client c)
{ {
return world.Players.FirstOrDefault(p => p.ClientIndex == c.Index && p.PlayerReference.Playable); return Array.Find(world.Players, p => p.ClientIndex == c.Index && p.PlayerReference.Playable);
} }
static bool OrderNotFromServerOrWorldIsReplay(int clientId, World world) => clientId != 0 || (world != null && world.IsReplay); static bool OrderNotFromServerOrWorldIsReplay(int clientId, World world) => clientId != 0 || (world != null && world.IsReplay);
@@ -184,12 +185,12 @@ namespace OpenRA.Network
if (!string.IsNullOrEmpty(order.TargetString)) if (!string.IsNullOrEmpty(order.TargetString))
{ {
var data = MiniYaml.FromString(order.TargetString); var data = MiniYaml.FromString(order.TargetString);
var saveLastOrdersFrame = data.FirstOrDefault(n => n.Key == "SaveLastOrdersFrame"); var saveLastOrdersFrame = data.Find(n => n.Key == "SaveLastOrdersFrame");
if (saveLastOrdersFrame != null) if (saveLastOrdersFrame != null)
orderManager.GameSaveLastFrame = orderManager.GameSaveLastFrame =
FieldLoader.GetValue<int>("saveLastOrdersFrame", saveLastOrdersFrame.Value.Value); FieldLoader.GetValue<int>("saveLastOrdersFrame", saveLastOrdersFrame.Value.Value);
var saveSyncFrame = data.FirstOrDefault(n => n.Key == "SaveSyncFrame"); var saveSyncFrame = data.Find(n => n.Key == "SaveSyncFrame");
if (saveSyncFrame != null) if (saveSyncFrame != null)
orderManager.GameSaveLastSyncFrame = orderManager.GameSaveLastSyncFrame =
FieldLoader.GetValue<int>("SaveSyncFrame", saveSyncFrame.Value.Value); FieldLoader.GetValue<int>("SaveSyncFrame", saveSyncFrame.Value.Value);
@@ -374,7 +375,7 @@ namespace OpenRA.Network
var strings = node.Key.Split('@'); var strings = node.Key.Split('@');
if (strings[0] == "ConnectionQuality") if (strings[0] == "ConnectionQuality")
{ {
var client = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.Index == Exts.ParseInt32Invariant(strings[1])); var client = orderManager.LobbyInfo.Clients.Find(c => c.Index == Exts.ParseInt32Invariant(strings[1]));
if (client != null) if (client != null)
client.ConnectionQuality = FieldLoader.GetValue<Session.ConnectionQuality>("ConnectionQuality", node.Value.Value); client.ConnectionQuality = FieldLoader.GetValue<Session.ConnectionQuality>("ConnectionQuality", node.Value.Value);
} }

View File

@@ -109,14 +109,14 @@ namespace OpenRA
.Where(f => !requireSelectable || f.Selectable) .Where(f => !requireSelectable || f.Selectable)
.ToList(); .ToList();
var selected = selectableFactions.FirstOrDefault(f => f.InternalName == factionName) var selected = selectableFactions.Find(f => f.InternalName == factionName)
?? selectableFactions.Random(playerRandom); ?? selectableFactions.Random(playerRandom);
// Don't loop infinite // Don't loop infinite
for (var i = 0; i <= 10 && selected.RandomFactionMembers.Count > 0; i++) for (var i = 0; i <= 10 && selected.RandomFactionMembers.Count > 0; i++)
{ {
var faction = selected.RandomFactionMembers.Random(playerRandom); var faction = selected.RandomFactionMembers.Random(playerRandom);
selected = selectableFactions.FirstOrDefault(f => f.InternalName == faction); selected = selectableFactions.Find(f => f.InternalName == faction);
if (selected == null) if (selected == null)
throw new YamlException($"Unknown faction: {faction}"); throw new YamlException($"Unknown faction: {faction}");
@@ -179,7 +179,7 @@ namespace OpenRA
else else
{ {
// Map player // Map player
ClientIndex = world.LobbyInfo.Clients.FirstOrDefault(c => c.IsAdmin)?.Index ?? 0; // Owned by the host (TODO: fix this) ClientIndex = world.LobbyInfo.Clients.Find(c => c.IsAdmin)?.Index ?? 0; // Owned by the host (TODO: fix this)
Color = pr.Color; Color = pr.Color;
PlayerName = pr.Name; PlayerName = pr.Name;
NonCombatant = pr.NonCombatant; NonCombatant = pr.NonCombatant;

View File

@@ -211,7 +211,7 @@ namespace OpenRA.Scripting
var bindings = Game.ModData.ObjectCreator.GetTypesImplementing<ScriptGlobal>(); var bindings = Game.ModData.ObjectCreator.GetTypesImplementing<ScriptGlobal>();
foreach (var b in bindings) foreach (var b in bindings)
{ {
var ctor = b.GetConstructors(BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(c => var ctor = Array.Find(b.GetConstructors(BindingFlags.Public | BindingFlags.Instance), c =>
{ {
var p = c.GetParameters(); var p = c.GetParameters();
return p.Length == 1 && p.First().ParameterType == typeof(ScriptContext); return p.Length == 1 && p.First().ParameterType == typeof(ScriptContext);

View File

@@ -1160,7 +1160,7 @@ namespace OpenRA.Server
} }
public bool HasClientWonOrLost(Session.Client client) => public bool HasClientWonOrLost(Session.Client client) =>
worldPlayers.FirstOrDefault(p => p?.ClientIndex == client.Index)?.Outcome != WinState.Undefined; worldPlayers.Find(p => p?.ClientIndex == client.Index)?.Outcome != WinState.Undefined;
public void DropClient(Connection toDrop) public void DropClient(Connection toDrop)
{ {
@@ -1169,7 +1169,7 @@ namespace OpenRA.Server
orderBuffer?.RemovePlayer(toDrop.PlayerIndex); orderBuffer?.RemovePlayer(toDrop.PlayerIndex);
Conns.Remove(toDrop); Conns.Remove(toDrop);
var dropClient = LobbyInfo.Clients.FirstOrDefault(c => c.Index == toDrop.PlayerIndex); var dropClient = LobbyInfo.Clients.Find(c => c.Index == toDrop.PlayerIndex);
if (dropClient == null) if (dropClient == null)
{ {
toDrop.Dispose(); toDrop.Dispose();
@@ -1251,7 +1251,7 @@ namespace OpenRA.Server
lock (LobbyInfo) lock (LobbyInfo)
{ {
// TODO: Only need to sync the specific client that has changed to avoid conflicts! // TODO: Only need to sync the specific client that has changed to avoid conflicts!
var clientData = LobbyInfo.Clients.Select(client => client.Serialize()).ToList(); var clientData = LobbyInfo.Clients.ConvertAll(client => client.Serialize());
DispatchServerOrdersToClients(Order.FromTargetString("SyncLobbyClients", clientData.WriteToString(), true)); DispatchServerOrdersToClients(Order.FromTargetString("SyncLobbyClients", clientData.WriteToString(), true));

View File

@@ -348,7 +348,7 @@ namespace OpenRA
LoadSectionYaml(yamlSection.Value, settingsSection); LoadSectionYaml(yamlSection.Value, settingsSection);
} }
var keysNode = yamlCache.FirstOrDefault(n => n.Key == "Keys"); var keysNode = yamlCache.Find(n => n.Key == "Keys");
if (keysNode != null) if (keysNode != null)
foreach (var node in keysNode.Value.Nodes) foreach (var node in keysNode.Value.Nodes)
if (node.Key != null) if (node.Key != null)
@@ -370,10 +370,10 @@ namespace OpenRA
public void Save() public void Save()
{ {
var yamlCacheBuilder = yamlCache.Select(n => new MiniYamlNodeBuilder(n)).ToList(); var yamlCacheBuilder = yamlCache.ConvertAll(n => new MiniYamlNodeBuilder(n));
foreach (var kv in Sections) foreach (var kv in Sections)
{ {
var sectionYaml = yamlCacheBuilder.FirstOrDefault(x => x.Key == kv.Key); var sectionYaml = yamlCacheBuilder.Find(x => x.Key == kv.Key);
if (sectionYaml == null) if (sectionYaml == null)
{ {
sectionYaml = new MiniYamlNodeBuilder(kv.Key, new MiniYamlBuilder("")); sectionYaml = new MiniYamlNodeBuilder(kv.Key, new MiniYamlBuilder(""));
@@ -403,7 +403,7 @@ namespace OpenRA
} }
} }
var keysYaml = yamlCacheBuilder.FirstOrDefault(x => x.Key == "Keys"); var keysYaml = yamlCacheBuilder.Find(x => x.Key == "Keys");
if (keysYaml == null) if (keysYaml == null)
{ {
keysYaml = new MiniYamlNodeBuilder("Keys", new MiniYamlBuilder("")); keysYaml = new MiniYamlNodeBuilder("Keys", new MiniYamlBuilder(""));

View File

@@ -59,7 +59,7 @@ namespace OpenRA.UtilityCommands
modData.ModFiles.TryGetPackageContaining(chrome, out var chromePackage, out var chromeName); modData.ModFiles.TryGetPackageContaining(chrome, out var chromePackage, out var chromeName);
var chromePath = Path.Combine(chromePackage.Name, chromeName); var chromePath = Path.Combine(chromePackage.Name, chromeName);
var yaml = MiniYaml.FromFile(chromePath, false).Select(n => new MiniYamlNodeBuilder(n)).ToList(); var yaml = MiniYaml.FromFile(chromePath, false).ConvertAll(n => new MiniYamlNodeBuilder(n));
chromeFiles.Add((chromePath, yaml)); chromeFiles.Add((chromePath, yaml));
var translationCandidates = new List<TranslationCandidate>(); var translationCandidates = new List<TranslationCandidate>();

View File

@@ -9,6 +9,7 @@
*/ */
#endregion #endregion
using System;
using System.Linq; using System.Linq;
using Eluant; using Eluant;
using OpenRA.Mods.Cnc.Activities; using OpenRA.Mods.Cnc.Activities;
@@ -32,7 +33,7 @@ namespace OpenRA.Mods.Cnc.Scripting
[Desc("Infiltrate the target actor.")] [Desc("Infiltrate the target actor.")]
public void Infiltrate(Actor target) public void Infiltrate(Actor target)
{ {
var infiltrates = infiltratesTraits.FirstOrDefault(x => !x.IsTraitDisabled && x.Info.Types.Overlaps(target.GetEnabledTargetTypes())); var infiltrates = Array.Find(infiltratesTraits, x => !x.IsTraitDisabled && x.Info.Types.Overlaps(target.GetEnabledTargetTypes()));
if (infiltrates == null) if (infiltrates == null)
throw new LuaException($"{Self} tried to infiltrate invalid target {target}!"); throw new LuaException($"{Self} tried to infiltrate invalid target {target}!");

View File

@@ -161,7 +161,7 @@ namespace OpenRA.Mods.Cnc.Traits
if (!available || order.ExtraData != 1) if (!available || order.ExtraData != 1)
return; return;
var power = Instances.FirstOrDefault(i => !i.IsTraitPaused); var power = Instances.Find(i => !i.IsTraitPaused);
if (power == null) if (power == null)
return; return;

View File

@@ -35,7 +35,7 @@ namespace OpenRA.Mods.Cnc.UtilityCommands
var inputFiles = GlobArgs(args).OrderBy(a => a).ToList(); var inputFiles = GlobArgs(args).OrderBy(a => a).ToList();
var dest = inputFiles[0].Split('-').First() + ".shp"; var dest = inputFiles[0].Split('-').First() + ".shp";
var frames = inputFiles.Select(a => new Png(File.OpenRead(a))).ToList(); var frames = inputFiles.ConvertAll(a => new Png(File.OpenRead(a)));
if (frames.Any(f => f.Type != SpriteFrameType.Indexed8)) if (frames.Any(f => f.Type != SpriteFrameType.Indexed8))
throw new InvalidOperationException("All frames must be paletted"); throw new InvalidOperationException("All frames must be paletted");

View File

@@ -9,6 +9,7 @@
*/ */
#endregion #endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using OpenRA.Activities; using OpenRA.Activities;
@@ -175,7 +176,7 @@ namespace OpenRA.Mods.Common.Activities
{ {
if (ammoPools != null) if (ammoPools != null)
{ {
var pool = ammoPools.FirstOrDefault(x => x.Info.Name == minelayer.Info.AmmoPoolName); var pool = Array.Find(ammoPools, x => x.Info.Name == minelayer.Info.AmmoPoolName);
if (pool == null) if (pool == null)
return false; return false;
@@ -193,7 +194,7 @@ namespace OpenRA.Mods.Common.Activities
{ {
if (ammoPools != null) if (ammoPools != null)
{ {
var pool = ammoPools.FirstOrDefault(x => x.Info.Name == minelayer.Info.AmmoPoolName); var pool = Array.Find(ammoPools, x => x.Info.Name == minelayer.Info.AmmoPoolName);
if (pool == null) if (pool == null)
return false; return false;

View File

@@ -141,7 +141,7 @@ namespace OpenRA.Mods.Common.Activities
QueueChild(move.MoveWithinRange(host, closeEnough, targetLineColor: moveInfo.GetTargetLineColor())); QueueChild(move.MoveWithinRange(host, closeEnough, targetLineColor: moveInfo.GetTargetLineColor()));
var delta = (self.CenterPosition - host.CenterPosition).LengthSquared; var delta = (self.CenterPosition - host.CenterPosition).LengthSquared;
transportCallers.FirstOrDefault(t => t.MinimumDistance.LengthSquared < delta)?.RequestTransport(self, targetCell); Array.Find(transportCallers, t => t.MinimumDistance.LengthSquared < delta)?.RequestTransport(self, targetCell);
return false; return false;
} }
@@ -256,7 +256,7 @@ namespace OpenRA.Mods.Common.Activities
void RepairTick(Actor self) void RepairTick(Actor self)
{ {
var repairsUnits = allRepairsUnits.FirstOrDefault(r => !r.IsTraitDisabled && !r.IsTraitPaused); var repairsUnits = Array.Find(allRepairsUnits, r => !r.IsTraitDisabled && !r.IsTraitPaused);
if (repairsUnits == null) if (repairsUnits == null)
{ {
if (!allRepairsUnits.Any(r => r.IsTraitPaused)) if (!allRepairsUnits.Any(r => r.IsTraitPaused))

View File

@@ -89,7 +89,7 @@ namespace OpenRA.Mods.Common.FileFormats
public void ExtractFile(string filename, Stream output, Action<int> onProgress = null) public void ExtractFile(string filename, Stream output, Action<int> onProgress = null)
{ {
var file = files.FirstOrDefault(f => f.FileName == filename); var file = Array.Find(files, f => f.FileName == filename);
if (file == null) if (file == null)
throw new FileNotFoundException(filename); throw new FileNotFoundException(filename);

View File

@@ -69,7 +69,7 @@ namespace OpenRA.Mods.Common.HitShapes
var topRight = new int2(BottomRight.X, TopLeft.Y); var topRight = new int2(BottomRight.X, TopLeft.Y);
var bottomLeft = new int2(TopLeft.X, BottomRight.Y); var bottomLeft = new int2(TopLeft.X, BottomRight.Y);
var corners = new[] { TopLeft, BottomRight, topRight, bottomLeft }; var corners = new[] { TopLeft, BottomRight, topRight, bottomLeft };
OuterRadius = new WDist(corners.Select(x => x.Length).Max()); OuterRadius = new WDist(corners.Max(x => x.Length));
combatOverlayVertsTop = new WVec[] combatOverlayVertsTop = new WVec[]
{ {

View File

@@ -9,6 +9,7 @@
*/ */
#endregion #endregion
using System;
using System.Linq; using System.Linq;
using Eluant; using Eluant;
using OpenRA.Scripting; using OpenRA.Scripting;
@@ -24,7 +25,7 @@ namespace OpenRA.Mods.Common.Scripting
[Desc("Returns the player with the specified internal name, or nil if a match is not found.")] [Desc("Returns the player with the specified internal name, or nil if a match is not found.")]
public Player GetPlayer(string name) public Player GetPlayer(string name)
{ {
return Context.World.Players.FirstOrDefault(p => p.InternalName == name); return Array.Find(Context.World.Players, p => p.InternalName == name);
} }
[Desc("Returns a table of players filtered by the specified function.")] [Desc("Returns a table of players filtered by the specified function.")]

View File

@@ -9,6 +9,7 @@
*/ */
#endregion #endregion
using System;
using System.Linq; using System.Linq;
using Eluant; using Eluant;
using OpenRA.Mods.Common.Traits; using OpenRA.Mods.Common.Traits;
@@ -33,7 +34,7 @@ namespace OpenRA.Mods.Common.Scripting
[Desc("Returns the count of the actor's specified ammopool.")] [Desc("Returns the count of the actor's specified ammopool.")]
public int AmmoCount(string poolName = "primary") public int AmmoCount(string poolName = "primary")
{ {
var pool = ammoPools.FirstOrDefault(a => a.Info.Name == poolName); var pool = Array.Find(ammoPools, a => a.Info.Name == poolName);
if (pool == null) if (pool == null)
throw new LuaException($"Invalid ammopool name {poolName} queried on actor {self}."); throw new LuaException($"Invalid ammopool name {poolName} queried on actor {self}.");
@@ -43,7 +44,7 @@ namespace OpenRA.Mods.Common.Scripting
[Desc("Returns the maximum count of ammo the actor can load.")] [Desc("Returns the maximum count of ammo the actor can load.")]
public int MaximumAmmoCount(string poolName = "primary") public int MaximumAmmoCount(string poolName = "primary")
{ {
var pool = ammoPools.FirstOrDefault(a => a.Info.Name == poolName); var pool = Array.Find(ammoPools, a => a.Info.Name == poolName);
if (pool == null) if (pool == null)
throw new LuaException($"Invalid ammopool name {poolName} queried on actor {self}."); throw new LuaException($"Invalid ammopool name {poolName} queried on actor {self}.");
@@ -54,7 +55,7 @@ namespace OpenRA.Mods.Common.Scripting
"(Use a negative amount to remove ammo.)")] "(Use a negative amount to remove ammo.)")]
public void Reload(string poolName = "primary", int amount = 1) public void Reload(string poolName = "primary", int amount = 1)
{ {
var pool = ammoPools.FirstOrDefault(a => a.Info.Name == poolName); var pool = Array.Find(ammoPools, a => a.Info.Name == poolName);
if (pool == null) if (pool == null)
throw new LuaException($"Invalid ammopool name {poolName} queried on actor {self}."); throw new LuaException($"Invalid ammopool name {poolName} queried on actor {self}.");

View File

@@ -9,6 +9,7 @@
*/ */
#endregion #endregion
using System;
using System.Linq; using System.Linq;
using Eluant; using Eluant;
using OpenRA.Mods.Common.Traits; using OpenRA.Mods.Common.Traits;
@@ -33,8 +34,7 @@ namespace OpenRA.Mods.Common.Scripting
"If duration > 0 the condition will be automatically revoked after the defined number of ticks.")] "If duration > 0 the condition will be automatically revoked after the defined number of ticks.")]
public int GrantCondition(string condition, int duration = 0) public int GrantCondition(string condition, int duration = 0)
{ {
var external = externalConditions var external = Array.Find(externalConditions, t => t.Info.Condition == condition && t.CanGrantCondition(this));
.FirstOrDefault(t => t.Info.Condition == condition && t.CanGrantCondition(this));
if (external == null) if (external == null)
throw new LuaException($"Condition `{condition}` has not been listed on an enabled ExternalCondition trait"); throw new LuaException($"Condition `{condition}` has not been listed on an enabled ExternalCondition trait");

View File

@@ -9,6 +9,7 @@
*/ */
#endregion #endregion
using System;
using System.Linq; using System.Linq;
using Eluant; using Eluant;
using OpenRA.Mods.Common.Traits; using OpenRA.Mods.Common.Traits;
@@ -32,8 +33,7 @@ namespace OpenRA.Mods.Common.Scripting
"If duration > 0 the condition will be automatically revoked after the defined number of ticks.")] "If duration > 0 the condition will be automatically revoked after the defined number of ticks.")]
public int GrantCondition(string condition, int duration = 0) public int GrantCondition(string condition, int duration = 0)
{ {
var external = externalConditions var external = Array.Find(externalConditions, t => t.Info.Condition == condition && t.CanGrantCondition(this));
.FirstOrDefault(t => t.Info.Condition == condition && t.CanGrantCondition(this));
if (external == null) if (external == null)
throw new LuaException($"Condition `{condition}` has not been listed on an enabled ExternalCondition trait"); throw new LuaException($"Condition `{condition}` has not been listed on an enabled ExternalCondition trait");

View File

@@ -47,7 +47,7 @@ namespace OpenRA.Mods.Common.Scripting
{ {
get get
{ {
var c = Player.World.LobbyInfo.Clients.FirstOrDefault(i => i.Index == Player.ClientIndex); var c = Player.World.LobbyInfo.Clients.Find(i => i.Index == Player.ClientIndex);
return c?.Team ?? 0; return c?.Team ?? 0;
} }
} }
@@ -57,7 +57,7 @@ namespace OpenRA.Mods.Common.Scripting
{ {
get get
{ {
var c = Player.World.LobbyInfo.Clients.FirstOrDefault(i => i.Index == Player.ClientIndex); var c = Player.World.LobbyInfo.Clients.Find(i => i.Index == Player.ClientIndex);
return c?.Handicap ?? 0; return c?.Handicap ?? 0;
} }
} }

View File

@@ -187,8 +187,7 @@ namespace OpenRA.Mods.Common.Scripting
if (triggers.HasAnyCallbacksFor(Trigger.OnProduction)) if (triggers.HasAnyCallbacksFor(Trigger.OnProduction))
return true; return true;
return queues.Where(q => GetBuildableInfo(actorType).Queue.Contains(q.Info.Type)) return queues.Any(q => GetBuildableInfo(actorType).Queue.Contains(q.Info.Type) && q.AllQueued().Any());
.Any(q => q.AllQueued().Any());
} }
BuildableInfo GetBuildableInfo(string actorType) BuildableInfo GetBuildableInfo(string actorType)

View File

@@ -278,7 +278,7 @@ namespace OpenRA.Mods.Common.Server
{ {
// Client 0 will always be the Host // Client 0 will always be the Host
// In some cases client 0 doesn't exist, so we untick all players // In some cases client 0 doesn't exist, so we untick all players
var host = server.LobbyInfo.Clients.FirstOrDefault(c => c.Index == 0); var host = server.LobbyInfo.Clients.Find(c => c.Index == 0);
if (host != null) if (host != null)
host.State = Session.ClientState.NotReady; host.State = Session.ClientState.NotReady;
else else
@@ -442,7 +442,7 @@ namespace OpenRA.Mods.Common.Server
} }
else else
{ {
var occupantConn = server.Conns.FirstOrDefault(c => c.PlayerIndex == occupant.Index); var occupantConn = server.Conns.Find(c => c.PlayerIndex == occupant.Index);
if (occupantConn != null) if (occupantConn != null)
{ {
server.SendOrderTo(conn, "ServerError", SlotClosed); server.SendOrderTo(conn, "ServerError", SlotClosed);
@@ -1143,7 +1143,7 @@ namespace OpenRA.Mods.Common.Server
if (spawnPoint == 0) if (spawnPoint == 0)
return true; return true;
var existingClient = server.LobbyInfo.Clients.FirstOrDefault(cc => cc.SpawnPoint == spawnPoint); var existingClient = server.LobbyInfo.Clients.Find(cc => cc.SpawnPoint == spawnPoint);
if (client != existingClient && !client.IsAdmin) if (client != existingClient && !client.IsAdmin)
{ {
server.SendLocalizedMessageTo(conn, AdminClearSpawn); server.SendLocalizedMessageTo(conn, AdminClearSpawn);
@@ -1200,7 +1200,7 @@ namespace OpenRA.Mods.Common.Server
return true; return true;
} }
if (server.LobbyInfo.Clients.Where(cc => cc != client).Any(cc => (cc.SpawnPoint == spawnPoint) && (cc.SpawnPoint != 0))) if (server.LobbyInfo.Clients.Any(cc => cc != client && (cc.SpawnPoint == spawnPoint) && (cc.SpawnPoint != 0)))
{ {
server.SendLocalizedMessageTo(conn, SpawnOccupied); server.SendLocalizedMessageTo(conn, SpawnOccupied);
return true; return true;

View File

@@ -165,7 +165,7 @@ namespace OpenRA.Mods.Common.Server
var slot = server.LobbyInfo.FirstEmptyBotSlot(); var slot = server.LobbyInfo.FirstEmptyBotSlot();
var bot = server.Map.PlayerActorInfo.TraitInfos<IBotInfo>().Select(t => t.Type).FirstOrDefault(); var bot = server.Map.PlayerActorInfo.TraitInfos<IBotInfo>().Select(t => t.Type).FirstOrDefault();
var botController = server.LobbyInfo.Clients.FirstOrDefault(c => c.IsAdmin); var botController = server.LobbyInfo.Clients.Find(c => c.IsAdmin);
if (slot != null && bot != null) if (slot != null && bot != null)
server.InterpretCommand($"slot_bot {slot} {botController.Index} {bot}", conn); server.InterpretCommand($"slot_bot {slot} {botController.Index} {bot}", conn);
} }

View File

@@ -9,6 +9,7 @@
*/ */
#endregion #endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using OpenRA.Mods.Common.Activities; using OpenRA.Mods.Common.Activities;
@@ -162,7 +163,7 @@ namespace OpenRA.Mods.Common.Traits
if (world.Map.Contains(cell)) if (world.Map.Contains(cell))
{ {
var explored = subject.Actor.Owner.Shroud.IsExplored(cell); var explored = subject.Actor.Owner.Shroud.IsExplored(cell);
var cannotMove = subjects.FirstOrDefault(a => !a.Trait.Info.MoveIntoShroud).Trait; var cannotMove = Array.Find(subjects, a => !a.Trait.Info.MoveIntoShroud).Trait;
var blocked = !explored && cannotMove != null; var blocked = !explored && cannotMove != null;
if (isAssaultMove) if (isAssaultMove)

View File

@@ -305,7 +305,7 @@ namespace OpenRA.Mods.Common.Traits
// HACK: Use of this function requires that there is one squad of this type. // HACK: Use of this function requires that there is one squad of this type.
Squad GetSquadOfType(SquadType type) Squad GetSquadOfType(SquadType type)
{ {
return Squads.FirstOrDefault(s => s.Type == type); return Squads.Find(s => s.Type == type);
} }
Squad RegisterNewSquad(IBot bot, SquadType type, (Actor Actor, WVec Offset) target = default) Squad RegisterNewSquad(IBot bot, SquadType type, (Actor Actor, WVec Offset) target = default)
@@ -446,7 +446,7 @@ namespace OpenRA.Mods.Common.Traits
ownUnits.First()) ownUnits.First())
.ToList(); .ToList();
if (AttackOrFleeFuzzy.Rush.CanAttack(ownUnits, enemies.Select(x => x.Actor).ToList())) if (AttackOrFleeFuzzy.Rush.CanAttack(ownUnits, enemies.ConvertAll(x => x.Actor)))
{ {
var target = enemies.Count > 0 ? enemies.Random(World.LocalRandom) : enemyBaseBuilder; var target = enemies.Count > 0 ? enemies.Random(World.LocalRandom) : enemyBaseBuilder;
var rush = GetSquadOfType(SquadType.Rush); var rush = GetSquadOfType(SquadType.Rush);
@@ -508,7 +508,7 @@ namespace OpenRA.Mods.Common.Traits
return new List<MiniYamlNode>() return new List<MiniYamlNode>()
{ {
new("Squads", "", Squads.Select(s => new MiniYamlNode("Squad", s.Serialize())).ToList()), new("Squads", "", Squads.ConvertAll(s => new MiniYamlNode("Squad", s.Serialize()))),
new("InitialBaseCenter", FieldSaver.FormatValue(initialBaseCenter)), new("InitialBaseCenter", FieldSaver.FormatValue(initialBaseCenter)),
new("UnitsHangingAroundTheBase", FieldSaver.FormatValue(unitsHangingAroundTheBase new("UnitsHangingAroundTheBase", FieldSaver.FormatValue(unitsHangingAroundTheBase
.Where(a => !unitCannotBeOrdered(a)) .Where(a => !unitCannotBeOrdered(a))

View File

@@ -57,7 +57,9 @@ namespace OpenRA.Mods.Common.Traits
.ThenBy(e => (actor.World.Map.CenterOfCell(actor.Location + e.Info.ExitCell) - pos).LengthSquared) .ThenBy(e => (actor.World.Map.CenterOfCell(actor.Location + e.Info.ExitCell) - pos).LengthSquared)
.ToList(); .ToList();
#pragma warning disable RCS1077 // Optimize LINQ method call.
return p != null ? all.FirstOrDefault(p) : all.FirstOrDefault(); return p != null ? all.FirstOrDefault(p) : all.FirstOrDefault();
#pragma warning restore RCS1077 // Optimize LINQ method call.
} }
public static IEnumerable<Exit> Exits(this Actor actor, string productionType = null) public static IEnumerable<Exit> Exits(this Actor actor, string productionType = null)

View File

@@ -9,6 +9,7 @@
*/ */
#endregion #endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using OpenRA.Mods.Common.Activities; using OpenRA.Mods.Common.Activities;
@@ -142,7 +143,7 @@ namespace OpenRA.Mods.Common.Traits
return; return;
var currentTransform = self.CurrentActivity as Transform; var currentTransform = self.CurrentActivity as Transform;
var transform = transforms.FirstOrDefault(t => !t.IsTraitDisabled && !t.IsTraitPaused); var transform = Array.Find(transforms, t => !t.IsTraitDisabled && !t.IsTraitPaused);
if (transform == null && currentTransform == null) if (transform == null && currentTransform == null)
return; return;

View File

@@ -9,6 +9,7 @@
*/ */
#endregion #endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using OpenRA.Mods.Common.Activities; using OpenRA.Mods.Common.Activities;
@@ -94,7 +95,7 @@ namespace OpenRA.Mods.Common.Traits
return; return;
var currentTransform = self.CurrentActivity as Transform; var currentTransform = self.CurrentActivity as Transform;
var transform = transforms.FirstOrDefault(t => !t.IsTraitDisabled && !t.IsTraitPaused); var transform = Array.Find(transforms, t => !t.IsTraitDisabled && !t.IsTraitPaused);
if (transform == null && currentTransform == null) if (transform == null && currentTransform == null)
return; return;

View File

@@ -9,6 +9,7 @@
*/ */
#endregion #endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using OpenRA.Mods.Common.Activities; using OpenRA.Mods.Common.Activities;
@@ -120,7 +121,7 @@ namespace OpenRA.Mods.Common.Traits
return; return;
var currentTransform = self.CurrentActivity as Transform; var currentTransform = self.CurrentActivity as Transform;
var transform = transforms.FirstOrDefault(t => !t.IsTraitDisabled && !t.IsTraitPaused); var transform = Array.Find(transforms, t => !t.IsTraitDisabled && !t.IsTraitPaused);
if (transform == null && currentTransform == null) if (transform == null && currentTransform == null)
return; return;

View File

@@ -9,6 +9,7 @@
*/ */
#endregion #endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using OpenRA.Mods.Common.Activities; using OpenRA.Mods.Common.Activities;
@@ -128,7 +129,7 @@ namespace OpenRA.Mods.Common.Traits
return; return;
var currentTransform = self.CurrentActivity as Transform; var currentTransform = self.CurrentActivity as Transform;
var transform = transforms.FirstOrDefault(t => !t.IsTraitDisabled && !t.IsTraitPaused); var transform = Array.Find(transforms, t => !t.IsTraitDisabled && !t.IsTraitPaused);
if (transform == null && currentTransform == null) if (transform == null && currentTransform == null)
return; return;

View File

@@ -9,6 +9,7 @@
*/ */
#endregion #endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using OpenRA.Mods.Common.Activities; using OpenRA.Mods.Common.Activities;
@@ -122,7 +123,7 @@ namespace OpenRA.Mods.Common.Traits
return; return;
var currentTransform = self.CurrentActivity as Transform; var currentTransform = self.CurrentActivity as Transform;
var transform = transforms.FirstOrDefault(t => !t.IsTraitDisabled && !t.IsTraitPaused); var transform = Array.Find(transforms, t => !t.IsTraitDisabled && !t.IsTraitPaused);
if (transform == null && currentTransform == null) if (transform == null && currentTransform == null)
return; return;

View File

@@ -84,7 +84,7 @@ namespace OpenRA.Mods.Common.Traits
{ {
if (external == null || !external.CanGrantCondition(self)) if (external == null || !external.CanGrantCondition(self))
{ {
external = externals.FirstOrDefault(t => t.CanGrantCondition(self)); external = externals.Find(t => t.CanGrantCondition(self));
if (external == null) if (external == null)
break; break;
} }

View File

@@ -310,7 +310,7 @@ namespace OpenRA.Mods.Common.Traits
protected override IEnumerable<IRenderable> Render(WorldRenderer wr, World world) { yield break; } protected override IEnumerable<IRenderable> Render(WorldRenderer wr, World world) { yield break; }
protected override IEnumerable<IRenderable> RenderAboveShroud(WorldRenderer wr, World world) protected override IEnumerable<IRenderable> RenderAboveShroud(WorldRenderer wr, World world)
{ {
var minelayer = minelayers.FirstOrDefault(m => m.IsInWorld && !m.IsDead); var minelayer = minelayers.Find(m => m.IsInWorld && !m.IsDead);
if (minelayer == null) if (minelayer == null)
yield break; yield break;

View File

@@ -84,7 +84,7 @@ namespace OpenRA.Mods.Common.Traits
if (allProductionPaused) if (allProductionPaused)
return; return;
var item = Queue.FirstOrDefault(i => !i.Paused); var item = Queue.Find(i => !i.Paused);
if (item == null) if (item == null)
return; return;

View File

@@ -9,8 +9,8 @@
*/ */
#endregion #endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using OpenRA.Graphics; using OpenRA.Graphics;
using OpenRA.Traits; using OpenRA.Traits;
@@ -34,7 +34,7 @@ namespace OpenRA.Mods.Common.Traits
// TODO: This won't make sense for MP saves // TODO: This won't make sense for MP saves
var localPlayer = worldRenderer.World.LocalPlayer; var localPlayer = worldRenderer.World.LocalPlayer;
if ((localPlayer != null && localPlayer.PlayerActor != self) || if ((localPlayer != null && localPlayer.PlayerActor != self) ||
(localPlayer == null && self.Owner != self.World.Players.FirstOrDefault(p => p.IsBot))) (localPlayer == null && self.Owner != Array.Find(self.World.Players, p => p.IsBot)))
return null; return null;
var nodes = new List<MiniYamlNode>() var nodes = new List<MiniYamlNode>()

View File

@@ -27,7 +27,7 @@ namespace OpenRA.Mods.Common.Traits
{ {
CancelUnbuildableItems(); CancelUnbuildableItems();
var item = Queue.FirstOrDefault(i => !i.Paused); var item = Queue.Find(i => !i.Paused);
if (item == null) if (item == null)
return; return;

View File

@@ -175,7 +175,7 @@ namespace OpenRA.Mods.Common.Traits
.Where(p => p.AcceptsPlug(plugInfo.Type)) .Where(p => p.AcceptsPlug(plugInfo.Type))
.ToList(); .ToList();
var pluggable = pluggables.FirstOrDefault(p => a.Location + p.Info.Offset == targetLocation) var pluggable = pluggables.Find(p => a.Location + p.Info.Offset == targetLocation)
?? pluggables.FirstOrDefault(); ?? pluggables.FirstOrDefault();
if (pluggable == null) if (pluggable == null)

View File

@@ -515,7 +515,7 @@ namespace OpenRA.Mods.Common.Traits
protected virtual void PauseProduction(string itemName, bool paused) protected virtual void PauseProduction(string itemName, bool paused)
{ {
Queue.FirstOrDefault(a => a.Item == itemName)?.Pause(paused); Queue.Find(a => a.Item == itemName)?.Pause(paused);
} }
protected virtual void CancelProduction(string itemName, uint numberToCancel) protected virtual void CancelProduction(string itemName, uint numberToCancel)

View File

@@ -11,7 +11,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using OpenRA.Graphics; using OpenRA.Graphics;
using OpenRA.Mods.Common.Widgets; using OpenRA.Mods.Common.Widgets;
using OpenRA.Orders; using OpenRA.Orders;
@@ -152,7 +151,7 @@ namespace OpenRA.Mods.Common.Traits
Arrow GetArrow(double degree) Arrow GetArrow(double degree)
{ {
var arrow = directionArrows.FirstOrDefault(d => d.EndAngle >= degree); var arrow = Array.Find(directionArrows, d => d.EndAngle >= degree);
return arrow ?? directionArrows[0]; return arrow ?? directionArrows[0];
} }

View File

@@ -222,7 +222,7 @@ namespace OpenRA.Mods.Common.Traits
if (!Ready) if (!Ready)
return; return;
var power = Instances.FirstOrDefault(i => !i.IsTraitPaused); var power = Instances.Find(i => !i.IsTraitPaused);
if (power == null) if (power == null)
return; return;

View File

@@ -332,7 +332,7 @@ namespace OpenRA.Mods.Common.Traits
public EditorActorPreview this[string id] public EditorActorPreview this[string id]
{ {
get { return previews.FirstOrDefault(p => p.ID.Equals(id, StringComparison.OrdinalIgnoreCase)); } get { return previews.Find(p => p.ID.Equals(id, StringComparison.OrdinalIgnoreCase)); }
} }
} }
} }

View File

@@ -37,7 +37,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules
{ {
// Keep a resolved copy of the sequences so we can account for values imported through inheritance or Defaults. // Keep a resolved copy of the sequences so we can account for values imported through inheritance or Defaults.
// This will be modified during processing, so take a deep copy to avoid side-effects on other update rules. // This will be modified during processing, so take a deep copy to avoid side-effects on other update rules.
this.resolvedImagesNodes = MiniYaml.FromString(resolvedImagesNodes.WriteToString()).Select(n => new MiniYamlNodeBuilder(n)).ToList(); this.resolvedImagesNodes = MiniYaml.FromString(resolvedImagesNodes.WriteToString()).ConvertAll(n => new MiniYamlNodeBuilder(n));
var requiredMetadata = new HashSet<string>(); var requiredMetadata = new HashSet<string>();
foreach (var imageNode in resolvedImagesNodes) foreach (var imageNode in resolvedImagesNodes)
@@ -213,7 +213,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules
{ {
resolvedDefaultsNode.Value.Nodes.Select(n => n.Build()).ToArray(), resolvedDefaultsNode.Value.Nodes.Select(n => n.Build()).ToArray(),
resolvedSequenceNode.Value.Nodes.Select(n => n.Build()).ToArray() resolvedSequenceNode.Value.Nodes.Select(n => n.Build()).ToArray()
}).Select(n => new MiniYamlNodeBuilder(n)).ToList(); }).ConvertAll(n => new MiniYamlNodeBuilder(n));
resolvedSequenceNode.Value.Value ??= resolvedDefaultsNode.Value.Value; resolvedSequenceNode.Value.Value ??= resolvedDefaultsNode.Value.Value;
} }
} }

View File

@@ -45,7 +45,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules
harvesters[actorNode.Key] = harvesterNode.ChildrenMatching("DeliveryBuildings", includeRemovals: false) harvesters[actorNode.Key] = harvesterNode.ChildrenMatching("DeliveryBuildings", includeRemovals: false)
.FirstOrDefault()?.NodeValue<HashSet<string>>() ?? new HashSet<string>(); .FirstOrDefault()?.NodeValue<HashSet<string>>() ?? new HashSet<string>();
if (actorNode.ChildrenMatching("Refinery", includeRemovals: false).FirstOrDefault() != null) if (actorNode.ChildrenMatching("Refinery", includeRemovals: false).Any())
refineries.Add(actorNode.Key.ToLowerInvariant()); refineries.Add(actorNode.Key.ToLowerInvariant());
} }
@@ -102,7 +102,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules
refineryNode.RemoveNode(dockOffsetNode); refineryNode.RemoveNode(dockOffsetNode);
} }
var buildingNode = actorNode.Value.Nodes.FirstOrDefault(n => buildings.Any(b => n.KeyMatches(b, includeRemovals: false))); var buildingNode = actorNode.Value.Nodes.Find(n => buildings.Any(b => n.KeyMatches(b, includeRemovals: false)));
if (buildingNode != null) if (buildingNode != null)
{ {
var dimensions = buildingNode.ChildrenMatching("Dimensions", includeRemovals: false).FirstOrDefault()?.NodeValue<CVec>() ?? new CVec(1, 1); var dimensions = buildingNode.ChildrenMatching("Dimensions", includeRemovals: false).FirstOrDefault()?.NodeValue<CVec>() ?? new CVec(1, 1);

View File

@@ -9,6 +9,7 @@
*/ */
#endregion #endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using OpenRA.Mods.Common.UpdateRules.Rules; using OpenRA.Mods.Common.UpdateRules.Rules;
@@ -98,7 +99,7 @@ namespace OpenRA.Mods.Common.UpdateRules
if (namedType != null && namedType.IsSubclassOf(typeof(UpdateRule))) if (namedType != null && namedType.IsSubclassOf(typeof(UpdateRule)))
return new[] { (UpdateRule)objectCreator.CreateBasic(namedType) }; return new[] { (UpdateRule)objectCreator.CreateBasic(namedType) };
return Paths.FirstOrDefault(p => p.source == source)?.Rules(chain); return Array.Find(Paths, p => p.source == source)?.Rules(chain);
} }
public static IEnumerable<string> KnownPaths { get { return Paths.Select(p => p.source); } } public static IEnumerable<string> KnownPaths { get { return Paths.Select(p => p.source); } }

View File

@@ -35,7 +35,7 @@ namespace OpenRA.Mods.Common.UpdateRules
continue; continue;
} }
yaml.Add(((IReadWritePackage)package, name, MiniYaml.FromStream(package.GetStream(name), name, false).Select(n => new MiniYamlNodeBuilder(n)).ToList())); yaml.Add(((IReadWritePackage)package, name, MiniYaml.FromStream(package.GetStream(name), name, false).ConvertAll(n => new MiniYamlNodeBuilder(n))));
} }
return yaml; return yaml;
@@ -68,7 +68,7 @@ namespace OpenRA.Mods.Common.UpdateRules
{ {
// Ignore any files that aren't in the map bundle // Ignore any files that aren't in the map bundle
if (!filename.Contains('|') && mapPackage.Contains(filename)) if (!filename.Contains('|') && mapPackage.Contains(filename))
fileSet.Add((mapPackage, filename, MiniYaml.FromStream(mapPackage.GetStream(filename), filename, false).Select(n => new MiniYamlNodeBuilder(n)).ToList())); fileSet.Add((mapPackage, filename, MiniYaml.FromStream(mapPackage.GetStream(filename), filename, false).ConvertAll(n => new MiniYamlNodeBuilder(n))));
else if (modData.ModFiles.Exists(filename)) else if (modData.ModFiles.Exists(filename))
externalFilenames.Add(filename); externalFilenames.Add(filename);
} }
@@ -177,9 +177,9 @@ namespace OpenRA.Mods.Common.UpdateRules
} }
if (mapNode != null && mapNode.Nodes.Count > 0) if (mapNode != null && mapNode.Nodes.Count > 0)
yaml.Add(mapNode.Nodes.Select(n => n.Build()).ToList()); yaml.Add(mapNode.Nodes.ConvertAll(n => n.Build()));
return MiniYaml.Merge(yaml).Select(n => new MiniYamlNodeBuilder(n)).ToList(); return MiniYaml.Merge(yaml).ConvertAll(n => new MiniYamlNodeBuilder(n));
} }
static IEnumerable<string> FilterExternalModFiles(ModData modData, IEnumerable<string> files, HashSet<string> externalFilenames) static IEnumerable<string> FilterExternalModFiles(ModData modData, IEnumerable<string> files, HashSet<string> externalFilenames)
@@ -241,7 +241,7 @@ namespace OpenRA.Mods.Common.UpdateRules
if (rule is IBeforeUpdateActors beforeActors) if (rule is IBeforeUpdateActors beforeActors)
{ {
var resolvedActors = MiniYaml.Load(modData.DefaultFileSystem, modData.Manifest.Rules, null) var resolvedActors = MiniYaml.Load(modData.DefaultFileSystem, modData.Manifest.Rules, null)
.Select(n => new MiniYamlNodeBuilder(n)).ToList(); .ConvertAll(n => new MiniYamlNodeBuilder(n));
manualSteps.AddRange(beforeActors.BeforeUpdateActors(modData, resolvedActors)); manualSteps.AddRange(beforeActors.BeforeUpdateActors(modData, resolvedActors));
} }
@@ -250,7 +250,7 @@ namespace OpenRA.Mods.Common.UpdateRules
if (rule is IBeforeUpdateWeapons beforeWeapons) if (rule is IBeforeUpdateWeapons beforeWeapons)
{ {
var resolvedWeapons = MiniYaml.Load(modData.DefaultFileSystem, modData.Manifest.Weapons, null) var resolvedWeapons = MiniYaml.Load(modData.DefaultFileSystem, modData.Manifest.Weapons, null)
.Select(n => new MiniYamlNodeBuilder(n)).ToList(); .ConvertAll(n => new MiniYamlNodeBuilder(n));
manualSteps.AddRange(beforeWeapons.BeforeUpdateWeapons(modData, resolvedWeapons)); manualSteps.AddRange(beforeWeapons.BeforeUpdateWeapons(modData, resolvedWeapons));
} }
@@ -259,7 +259,7 @@ namespace OpenRA.Mods.Common.UpdateRules
if (rule is IBeforeUpdateSequences beforeSequences) if (rule is IBeforeUpdateSequences beforeSequences)
{ {
var resolvedImages = MiniYaml.Load(modData.DefaultFileSystem, modData.Manifest.Sequences, null) var resolvedImages = MiniYaml.Load(modData.DefaultFileSystem, modData.Manifest.Sequences, null)
.Select(n => new MiniYamlNodeBuilder(n)).ToList(); .ConvertAll(n => new MiniYamlNodeBuilder(n));
manualSteps.AddRange(beforeSequences.BeforeUpdateSequences(modData, resolvedImages)); manualSteps.AddRange(beforeSequences.BeforeUpdateSequences(modData, resolvedImages));
} }

View File

@@ -11,7 +11,6 @@
using System; using System;
using System.IO; using System.IO;
using System.Linq;
using OpenRA.FileSystem; using OpenRA.FileSystem;
namespace OpenRA.Mods.Common.UtilityCommands namespace OpenRA.Mods.Common.UtilityCommands
@@ -47,7 +46,7 @@ namespace OpenRA.Mods.Common.UtilityCommands
var fs = map ?? modData.DefaultFileSystem; var fs = map ?? modData.DefaultFileSystem;
var topLevelNodes = MiniYaml.Load(fs, manifestNodes, mapProperty); var topLevelNodes = MiniYaml.Load(fs, manifestNodes, mapProperty);
return topLevelNodes.FirstOrDefault(n => n.Key == key); return topLevelNodes.Find(n => n.Key == key);
} }
} }
} }

View File

@@ -91,7 +91,7 @@ namespace OpenRA.Mods.Common.Warheads
falloffDistance = closestDistance; falloffDistance = closestDistance;
break; break;
case DamageCalculationType.ClosestTargetablePosition: case DamageCalculationType.ClosestTargetablePosition:
falloffDistance = victim.GetTargetablePositions().Select(x => (x - pos).Length).Min(); falloffDistance = victim.GetTargetablePositions().Min(x => (x - pos).Length);
break; break;
case DamageCalculationType.CenterPosition: case DamageCalculationType.CenterPosition:
falloffDistance = (victim.CenterPosition - pos).Length; falloffDistance = (victim.CenterPosition - pos).Length;

View File

@@ -146,8 +146,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic
if (map.Package != null) if (map.Package != null)
{ {
selectedDirectory = writableDirectories.FirstOrDefault(k => k.Folder.Contains(map.Package.Name)); selectedDirectory = writableDirectories.Find(k => k.Folder.Contains(map.Package.Name));
selectedDirectory ??= writableDirectories.FirstOrDefault(k => Directory.GetDirectories(k.Folder.Name).Any(f => f.Contains(map.Package.Name))); selectedDirectory ??= writableDirectories.Find(k => Directory.GetDirectories(k.Folder.Name).Any(f => f.Contains(map.Package.Name)));
} }
// Prioritize MapClassification.User directories over system directories // Prioritize MapClassification.User directories over system directories

View File

@@ -33,7 +33,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
void SelectTab(bool reverse) void SelectTab(bool reverse)
{ {
palette.CurrentQueue = queues.FirstOrDefault(q => q.Enabled); palette.CurrentQueue = Array.Find(queues, q => q.Enabled);
// When a tab is selected, scroll to the top because the current row position may be invalid for the new tab // When a tab is selected, scroll to the top because the current row position may be invalid for the new tab
palette.ScrollToTop(); palette.ScrollToTop();

View File

@@ -212,7 +212,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
} }
var localClient = orderManager.LocalClient; var localClient = orderManager.LocalClient;
var localPlayer = localClient == null ? null : world.Players.FirstOrDefault(player => player.ClientIndex == localClient.Index); var localPlayer = localClient == null ? null : Array.Find(world.Players, player => player.ClientIndex == localClient.Index);
bool LocalPlayerCanKick() => localClient != null bool LocalPlayerCanKick() => localClient != null
&& (Game.IsHost || ((!orderManager.LocalClient.IsObserver) && localPlayer.WinState == WinState.Undefined)); && (Game.IsHost || ((!orderManager.LocalClient.IsObserver) && localPlayer.WinState == WinState.Undefined));
bool CanClientBeKicked(Session.Client client, Func<bool> isVoteKick) => bool CanClientBeKicked(Session.Client client, Func<bool> isVoteKick) =>

View File

@@ -80,7 +80,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var downloadYaml = MiniYaml.Load(modFileSystem, content.Downloads, null); var downloadYaml = MiniYaml.Load(modFileSystem, content.Downloads, null);
modFileSystem.UnmountAll(); modFileSystem.UnmountAll();
var download = downloadYaml.FirstOrDefault(n => n.Key == content.QuickDownload); var download = downloadYaml.Find(n => n.Key == content.QuickDownload);
if (download == null) if (download == null)
throw new InvalidOperationException($"Mod QuickDownload `{content.QuickDownload}` definition not found."); throw new InvalidOperationException($"Mod QuickDownload `{content.QuickDownload}` definition not found.");

View File

@@ -274,7 +274,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var botTypes = map.PlayerActorInfo.TraitInfos<IBotInfo>().Select(t => t.Type); var botTypes = map.PlayerActorInfo.TraitInfos<IBotInfo>().Select(t => t.Type);
var options = new Dictionary<string, IEnumerable<DropDownOption>>(); var options = new Dictionary<string, IEnumerable<DropDownOption>>();
var botController = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.IsAdmin); var botController = orderManager.LobbyInfo.Clients.Find(c => c.IsAdmin);
if (orderManager.LobbyInfo.Slots.Values.Any(s => s.AllowBots)) if (orderManager.LobbyInfo.Slots.Values.Any(s => s.AllowBots))
{ {
var botOptions = new List<DropDownOption>() var botOptions = new List<DropDownOption>()

View File

@@ -74,7 +74,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
{ {
foreach (var b in map.PlayerActorInfo.TraitInfos<IBotInfo>()) foreach (var b in map.PlayerActorInfo.TraitInfos<IBotInfo>())
{ {
var botController = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.IsAdmin); var botController = orderManager.LobbyInfo.Clients.Find(c => c.IsAdmin);
bots.Add(new SlotDropDownOption(b.Name, bots.Add(new SlotDropDownOption(b.Name,
$"slot_bot {slot.PlayerReference} {botController.Index} {b.Type}", $"slot_bot {slot.PlayerReference} {botController.Index} {b.Type}",
() => client != null && client.Bot == b.Type)); () => client != null && client.Bot == b.Type));
@@ -266,7 +266,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
static void ClearPlayerSpawnPoint(OrderManager orderManager, MapPreviewWidget mapPreview, MapPreview preview, MouseInput mi) static void ClearPlayerSpawnPoint(OrderManager orderManager, MapPreviewWidget mapPreview, MapPreview preview, MouseInput mi)
{ {
var selectedSpawn = DetermineSelectedSpawnPoint(mapPreview, preview, mi); var selectedSpawn = DetermineSelectedSpawnPoint(mapPreview, preview, mi);
if (Game.IsHost || orderManager.LobbyInfo.Clients.FirstOrDefault(cc => cc.SpawnPoint == selectedSpawn) == orderManager.LocalClient) if (Game.IsHost || orderManager.LobbyInfo.Clients.Find(cc => cc.SpawnPoint == selectedSpawn) == orderManager.LocalClient)
orderManager.IssueOrder(Order.Command($"clear_spawn {selectedSpawn}")); orderManager.IssueOrder(Order.Command($"clear_spawn {selectedSpawn}"));
} }

View File

@@ -356,7 +356,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
gameModeDropdown.GetText = () => gameModeDropdown.GetText = () =>
{ {
var item = categories.FirstOrDefault(m => m.Category == category); var item = categories.Find(m => m.Category == category);
if (item == default((string, int))) if (item == default((string, int)))
item.Category = TranslationProvider.GetString(NoMatches); item.Category = TranslationProvider.GetString(NoMatches);

View File

@@ -696,7 +696,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
void SelectFirstVisibleReplay() void SelectFirstVisibleReplay()
{ {
SelectReplay(replays.FirstOrDefault(r => replayState[r].Visible)); SelectReplay(replays.Find(r => replayState[r].Visible));
} }
void SelectReplay(ReplayMetadata replay) void SelectReplay(ReplayMetadata replay)

View File

@@ -103,7 +103,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
videoVolumeSlider.OnChange += x => Game.Sound.VideoVolume = x; videoVolumeSlider.OnChange += x => Game.Sound.VideoVolume = x;
var devices = Game.Sound.AvailableDevices(); var devices = Game.Sound.AvailableDevices();
soundDevice = devices.FirstOrDefault(d => d.Device == ss.Device) ?? devices.First(); soundDevice = Array.Find(devices, d => d.Device == ss.Device) ?? devices.First();
var audioDeviceDropdown = panel.Get<DropDownButtonWidget>("AUDIO_DEVICE"); var audioDeviceDropdown = panel.Get<DropDownButtonWidget>("AUDIO_DEVICE");
audioDeviceDropdown.OnMouseDown = _ => ShowAudioDeviceDropdown(audioDeviceDropdown, devices, scrollPanel); audioDeviceDropdown.OnMouseDown = _ => ShowAudioDeviceDropdown(audioDeviceDropdown, devices, scrollPanel);

View File

@@ -38,7 +38,7 @@ namespace OpenRA.Mods.Common.Widgets
{ {
resourceType = value; resourceType = value;
if (resourceType != null) if (resourceType != null)
resourceRenderer = resourceRenderers.FirstOrDefault(r => r.ResourceTypes.Contains(resourceType)); resourceRenderer = Array.Find(resourceRenderers, r => r.ResourceTypes.Contains(resourceType));
else else
resourceRenderer = null; resourceRenderer = null;
} }

View File

@@ -10,7 +10,6 @@
#endregion #endregion
using System; using System;
using System.Linq;
using OpenRA.Graphics; using OpenRA.Graphics;
using OpenRA.Primitives; using OpenRA.Primitives;
using OpenRA.Widgets; using OpenRA.Widgets;
@@ -284,7 +283,7 @@ namespace OpenRA.Mods.Common.Widgets
public void ScrollToItem(string itemKey, bool smooth = false) public void ScrollToItem(string itemKey, bool smooth = false)
{ {
var item = Children.FirstOrDefault(c => c is ScrollItemWidget si && si.ItemKey == itemKey); var item = Children.Find(c => c is ScrollItemWidget si && si.ItemKey == itemKey);
if (item != null) if (item != null)
ScrollToItem(item, smooth); ScrollToItem(item, smooth);
@@ -292,7 +291,7 @@ namespace OpenRA.Mods.Common.Widgets
public void ScrollToSelectedItem() public void ScrollToSelectedItem()
{ {
var item = Children.FirstOrDefault(c => c is ScrollItemWidget si && si.IsSelected()); var item = Children.Find(c => c is ScrollItemWidget si && si.IsSelected());
if (item != null) if (item != null)
ScrollToItem(item); ScrollToItem(item);
@@ -469,7 +468,7 @@ namespace OpenRA.Mods.Common.Widgets
if (collection != col) if (collection != col)
return; return;
var widget = Children.FirstOrDefault(w => widgetItemEquals(w, item)); var widget = Children.Find(w => widgetItemEquals(w, item));
if (widget != null) if (widget != null)
RemoveChild(widget); RemoveChild(widget);
}); });