Skip to content

Commit

Permalink
Optimize collection access
Browse files Browse the repository at this point in the history
* Replace `First()` and `FirstOrDefault()` with index-based access (`[0]`) or `Find()` to enhance readability and performance.
* Change `Any()` to `Exists()` and `All()` to `TrueForAll()` for consistency and potential performance gains.
* Update lambda expressions to use pattern matching for null and property checks.
* Modify string comparisons to use single quotes for characters.
* Replace `Last()` with index-based access (`[^1]`).
  • Loading branch information
axunonb committed Oct 7, 2024
1 parent c84023c commit 555201e
Show file tree
Hide file tree
Showing 28 changed files with 42 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ protected override async Task CreateStandardNavigationNodes()
InsertTopNavigationNode(info, "Top_Teams");
}

InsertTopNavigationNode(home, NavigationNodes.First().Key);
InsertTopNavigationNode(home, NavigationNodes[0].Key);

#endregion
}
Expand Down
2 changes: 1 addition & 1 deletion League/BackgroundTasks/RankingUpdateTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ await TenantContext.DbContext.AppDb.TeamInRoundRepository.GetTeamInRoundAsync(
/***** Ranking table update *****/

// without played matches, neither ranking nor chart can be generated
if (matchesPlayed.All(mp => mp.RoundId != roundId))
if (matchesPlayed.TrueForAll(mp => mp.RoundId != roundId))
{
// Remove an existing ranking list for the round
await TenantContext.DbContext.AppDb.RankingRepository.ReplaceAsync(new RankingList(), roundId, cancellationToken);
Expand Down
4 changes: 2 additions & 2 deletions League/Components/MainNavigationComponentModelExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public static class MainNavigationComponentModelExtensions
/// <returns></returns>
public static bool HasVisibleChildNodes(this MainNavigationComponentModel.NavigationNode node)
{
return node.ChildNodes.Any(childNode => childNode.ShouldShow());
return node.ChildNodes.Exists(childNode => childNode.ShouldShow());
}

/// <summary>
Expand Down Expand Up @@ -104,7 +104,7 @@ public static bool IsActiveNode(this MainNavigationComponentModel model, Microso
/// <returns><see langref="true"/> if the node is visible and the node url is not null.</returns>
public static bool ShouldShow(this MainNavigationComponentModel.NavigationNode? node)
{
return node != null && (node.IsVisible && node.Url != null || node.ChildNodes.Any(n => n.ShouldShow()));
return node != null && (node is { IsVisible: true, Url: not null } || node.ChildNodes.Exists(n => n.ShouldShow()));
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion League/Controllers/Language.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public IActionResult Index(string? culture, string? uiCulture, string? returnUrl
}

// Preferred browser language is equal to language selected with query string
if (languages.Length == 0 || languages.First().StartsWith(requestCulture.Name, StringComparison.InvariantCultureIgnoreCase))
if (languages.Length == 0 || languages[0].StartsWith(requestCulture.Name, StringComparison.InvariantCultureIgnoreCase))
{
Response.Cookies.Delete(cookieProvider.CookieName);
Response.Cookies.Append(cookieProvider.CookieName, string.Empty, new CookieOptions
Expand Down
2 changes: 1 addition & 1 deletion League/Controllers/Match.cs
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ public async Task<IActionResult> EnterResult([FromForm] EnterResultViewModel? mo
if (permissionValidator.GetFailedFacts().Count != 0)
{
return View(ViewNames.Match.EnterResultNotAllowed,
(model.Tournament, permissionValidator.GetFailedFacts().First().Message));
(model.Tournament, permissionValidator.GetFailedFacts()[0].Message));
}

model.MapFormFieldsToEntity();
Expand Down
4 changes: 2 additions & 2 deletions League/Controllers/Ranking.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public async Task<IActionResult> AllTimeTournament(long?id, CancellationToken ca
var roundLegPeriods = await GetRoundLegPeriodsCached(rankingList, cancellationToken);

id ??= roundLegPeriods.Max(rlp => rlp.TournamentId);
if (roundLegPeriods.Count > 0 && roundLegPeriods.All(rlp => rlp.TournamentId != id))
if (roundLegPeriods.Count > 0 && roundLegPeriods.TrueForAll(rlp => rlp.TournamentId != id))
return Redirect(TenantLink.Action(nameof(AllTimeTournament), nameof(Ranking), new { id = string.Empty })!);

var model = new AllTimeTournamentModel(rankingList, roundLegPeriods) { SelectedTournamentId = id };
Expand All @@ -106,7 +106,7 @@ public async Task<IActionResult> AllTimeTeam(long? id, CancellationToken cancell
var rankingList = await GetRankingListCached(cancellationToken);
var roundLegPeriods = await GetRoundLegPeriodsCached(rankingList, cancellationToken);

if (rankingList.Count > 0 && rankingList.All(rl => rl.TeamId != id))
if (rankingList.Count > 0 && rankingList.TrueForAll(rl => rl.TeamId != id))
return Redirect(TenantLink.Action(nameof(AllTimeTournament), nameof(Ranking), new { id = string.Empty })!);

var model = new AllTimeTeamModel(rankingList, roundLegPeriods) { SelectedTeamId = id };
Expand Down
8 changes: 4 additions & 4 deletions League/Controllers/TeamApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ public async Task<IActionResult> SelectTeam([FromForm] ApplicationSelectTeamMode
public async Task<IActionResult> EditTeam(long teamId, CancellationToken cancellationToken)
{
var teamSelectModel = await GetTeamSelectModel(cancellationToken);
if (teamSelectModel.TeamsManagedByUser.All(t => t.TeamId != teamId))
if (teamSelectModel.TeamsManagedByUser.TrueForAll(t => t.TeamId != teamId))
{
return Redirect(TenantLink.Action(nameof(SelectTeam))!);
}
Expand Down Expand Up @@ -269,7 +269,7 @@ public async Task<IActionResult> EditTeam([FromForm] TeamEditModel teamEditModel

if (teamEntity.TeamInRounds.Any())
{
var tir = teamEntity.TeamInRounds.First();
var tir = teamEntity.TeamInRounds[0];
sessionModel.TeamInRound!.MapEntityToFormFields(tir);
sessionModel.TeamInRoundIsSet = true;
}
Expand Down Expand Up @@ -493,7 +493,7 @@ public async Task<IActionResult> Confirm(bool done, CancellationToken cancellati
teamInRoundEntity =
(await _appDb.TeamInRoundRepository.GetTeamInRoundAsync(
new PredicateExpression(TeamInRoundFields.Id == sessionModel.TeamInRound.Id),
cancellationToken)).First();
cancellationToken))[0];
}
}
catch (Exception e)
Expand Down Expand Up @@ -757,7 +757,7 @@ private async Task AddManagerToTeamEntity(TeamEntity teamEntity, CancellationTok
{
// Nothing to do, if the current user is already manager of this team
var mot = (await _appDb.ManagerOfTeamRepository.GetManagerOfTeamEntitiesAsync(new PredicateExpression(ManagerOfTeamFields.TeamId == teamEntity.Id),
cancellationToken)).FirstOrDefault(u => u.UserId == GetCurrentUserId());
cancellationToken)).Find(u => u.UserId == GetCurrentUserId());
if (mot == null)
{
mot = teamEntity.ManagerOfTeams.AddNew();
Expand Down
4 changes: 2 additions & 2 deletions League/Emailing/Creators/ChangeFixtureCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ public async IAsyncEnumerable<MailMergeMessage> GetMailMergeMessages(ITenantCont
.And(TeamUserRoundFields.TournamentId == tenantContext.TournamentContext.MatchPlanTournamentId)),
cancellationToken);

model.Username = teamUserRoundInfos.FirstOrDefault(tur => tur.UserId == Parameters.ChangedByUserId)?.CompleteName;
model.Username = teamUserRoundInfos.Find(tur => tur.UserId == Parameters.ChangedByUserId)?.CompleteName;
// User is not a team member, maybe an admin
model.Username ??= (await tenantContext.DbContext.AppDb.UserRepository.FindUserAsync(
new PredicateExpression(UserFields.Id == Parameters.ChangedByUserId), 1, cancellationToken)).First()
new PredicateExpression(UserFields.Id == Parameters.ChangedByUserId), 1, cancellationToken))[0]
.CompleteName;

var plainTextContent = await renderer.RenderAsync(Templates.Email.TemplateName.ChangeFixtureTxt, model,
Expand Down
2 changes: 1 addition & 1 deletion League/Emailing/Creators/ConfirmTeamApplicationCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public async IAsyncEnumerable<MailMergeMessage> GetMailMergeMessages(ITenantCont
var roundWithType = (await tenantContext.DbContext.AppDb.RoundRepository.GetRoundsWithTypeAsync(
new PredicateExpression(
RoundFields.TournamentId == tenantContext.TournamentContext.ApplicationTournamentId &
RoundFields.Id == Parameters.RoundId), cancellationToken)).First();
RoundFields.Id == Parameters.RoundId), cancellationToken))[0];

var teamUserRoundInfos = await tenantContext.DbContext.AppDb.TeamRepository.GetTeamUserRoundInfosAsync(
new PredicateExpression(TeamUserRoundFields.TeamId == Parameters.TeamId &
Expand Down
4 changes: 2 additions & 2 deletions League/Emailing/Creators/ResultEnteredCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ public async IAsyncEnumerable<MailMergeMessage> GetMailMergeMessages(ITenantCont
.And(TeamUserRoundFields.TournamentId == tenantContext.TournamentContext.MatchResultTournamentId)),
cancellationToken);

var username = teamUserRoundInfos.FirstOrDefault(tur => tur.UserId == Parameters.ChangedByUserId)?.CompleteName;
var username = teamUserRoundInfos.Find(tur => tur.UserId == Parameters.ChangedByUserId)?.CompleteName;
// User is not a team member, maybe an admin
username ??= (await tenantContext.DbContext.AppDb.UserRepository.FindUserAsync(
new PredicateExpression(UserFields.Id == Parameters.ChangedByUserId), 1, cancellationToken)).First()
new PredicateExpression(UserFields.Id == Parameters.ChangedByUserId), 1, cancellationToken))[0]
.CompleteName;

var model = new ResultEnteredModel
Expand Down
2 changes: 1 addition & 1 deletion League/LeagueStartup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ public static void ConfigureServices(WebApplicationBuilder builder, ILoggerFacto
}.LoadTenants();

var tenants = store.GetTenants().Values.ToList();
if (!tenants.Any(t => t.IsDefault)) throw new InvalidOperationException("No default tenant configuration found.");
if (!tenants.Exists(t => t.IsDefault)) throw new InvalidOperationException("No default tenant configuration found.");
tenants.ForEach(t =>
{
if (string.IsNullOrWhiteSpace(t.DbContext.ConnectionString))
Expand Down
2 changes: 1 addition & 1 deletion League/Models/MapViewModels/MapModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ private void PrepareAllVenues()
{
var locationJsObject = new StringBuilder("\n");

if (!Venues.Any(v => v.Longitude.HasValue && v.Latitude.HasValue))
if (!Venues.Exists(v => v is { Longitude: not null, Latitude: not null }))
return;

MaxLongitude = Venues.Max(l => l.Longitude)?.ToString("###.########", System.Globalization.CultureInfo.InvariantCulture);
Expand Down
2 changes: 1 addition & 1 deletion League/Models/RankingViewModels/AllTimeTeamModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public AllTimeTeamModel(List<RankingListRow> rankingList, List<RoundLegPeriodRow

public (string TeamName, string ClubName) GetSelectedTeam()
{
var rankRow = RankingList.FirstOrDefault(rl => rl.TeamId == SelectedTeamId);
var rankRow = RankingList.Find(rl => rl.TeamId == SelectedTeamId);
if (rankRow == null) return (string.Empty, string.Empty);

return (rankRow.TeamName, rankRow.ClubName);
Expand Down
2 changes: 1 addition & 1 deletion League/Models/TeamViewModels/TeamEditModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public void MapFormFieldsToEntity()
if (TeamEntity!.TeamInRounds.Any())
{
// Only the RoundId is updated, but not the TeamNameForRound!
TeamEntity.TeamInRounds.First().RoundId = Round.SelectedRoundId.Value;
TeamEntity.TeamInRounds[0].RoundId = Round.SelectedRoundId.Value;
}
else
{
Expand Down
2 changes: 1 addition & 1 deletion League/TagHelpers/Modal/SiteModalToggleTagHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ public class SiteModalToggleTagHelper : TagHelper
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.Attributes.SetAttribute("data-bs-toggle", "modal");
output.Attributes.SetAttribute("data-bs-target", ToggleModal != null && ToggleModal.StartsWith("#") ? ToggleModal : $"#{ToggleModal}");
output.Attributes.SetAttribute("data-bs-target", ToggleModal != null && ToggleModal.StartsWith('#') ? ToggleModal : $"#{ToggleModal}");
}
}
4 changes: 2 additions & 2 deletions League/Views/Map/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
@model League.Models.MapViewModels.MapModel
@inject IViewLocalizer Localizer
@{ ViewData["Title"] = Localizer["Venues"].Value + " - " + Model.Tournament?.Name;}
@if (!Model.Venues.Any(v => v is { Latitude: not null, Longitude: not null }))
@if (!Model.Venues.Exists(v => v is { Latitude: not null, Longitude: not null }))
{
<div class="row">
<div class="col-12 pb-2">
Expand All @@ -21,7 +21,7 @@
<h2 class="h2">@ViewData["Title"]</h2>
@if (Model.IsSingleValue)
{
var venue = Model.Venues.First();
var venue = Model.Venues[0];
<h3 class="h3"><i class="fas fa-map-marker-alt"></i> @venue.VenueName</h3>
<hr class="mb-4" />
}
Expand Down
2 changes: 1 addition & 1 deletion League/Views/Match/Fixtures.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
var activeRoundId = Model.ActiveRoundId ?? 0;
var rounds = Model.PlannedMatches.GroupBy(m => m.RoundName, (key, m) => new { RoundName = key, RoundId = m.First().RoundId, RoundDescription = m.First().RoundDescription, RoundTypeDescription = m.First().RoundTypeDescription })
.OrderBy(m => m.RoundName).ToList();
var useRecentRoundCookie = !(Model.ActiveRoundId.HasValue && rounds.Any(r => r.RoundId == Model.ActiveRoundId));
var useRecentRoundCookie = !(Model.ActiveRoundId.HasValue && rounds.Exists(r => r.RoundId == Model.ActiveRoundId));
if (useRecentRoundCookie) { activeRoundId = rounds.FirstOrDefault()?.RoundId ?? 0; }

string FmtDate(DateTime? matchDate)
Expand Down
4 changes: 2 additions & 2 deletions League/Views/Match/Results.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
var rounds = Model.CompletedMatches
.GroupBy(m => m.RoundName, (key, m) => new { RoundName = key, RoundId = m.First().RoundId, RoundDescription = m.First().RoundDescription, RoundTypeDescription = m.First().RoundTypeDescription })
.OrderBy(m => m.RoundName).ToList();
var useRecentRoundCookie = !(Model.ActiveRoundId.HasValue && rounds.Any(r => r.RoundId == Model.ActiveRoundId));
var useRecentRoundCookie = !(Model.ActiveRoundId.HasValue && rounds.Exists(r => r.RoundId == Model.ActiveRoundId));
if (useRecentRoundCookie) { activeRoundId = rounds.FirstOrDefault()?.RoundId ?? 0; }
MatchEntity ToMatchEntity(CompletedMatchRow cmr)
{
Expand Down Expand Up @@ -171,7 +171,7 @@
</table>
</div>
@{
if (Model.CompletedMatches.Any(m => m.RoundId == r.RoundId && m.IsOverruled))
if (Model.CompletedMatches.Exists(m => m.RoundId == r.RoundId && m.IsOverruled))
{
<div class="text-muted">
@(overruled) = @Localizer["Awarded points were adjusted manually"].
Expand Down
2 changes: 1 addition & 1 deletion League/Views/Ranking/Table.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
.GroupBy(m => m.RoundName, (key, m) => new { RoundName = key, RoundId = m.First()
.RoundId, RoundDescription = m.First().RoundDescription, RoundTypeDescription = m.First().RoundTypeDescription })
.OrderBy(m => m.RoundName).ToList();
var useRecentRoundCookie = !(Model.ActiveRoundId.HasValue && rounds.Any(r => r.RoundId == Model.ActiveRoundId));
var useRecentRoundCookie = !(Model.ActiveRoundId.HasValue && rounds.Exists(r => r.RoundId == Model.ActiveRoundId));
if (useRecentRoundCookie) { activeRoundId = rounds.FirstOrDefault()?.RoundId ?? 0; }
}
@functions {
Expand Down
2 changes: 1 addition & 1 deletion League/Views/Team/MyTeam.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
var teamPhotoInfo = Model.TeamPhotoStaticFile!.GetUriInfo(teamVenueInfo.TeamId);
var zonedLastModified = Model.TimeZoneConverter.ToZonedTime(teamPhotoInfo.Date)!;

<div class="tab-pane@{if (Model.TeamUserRoundInfos.Any(tvr => tvr.TeamId == Model.ActiveTeamId)){<text> show active</text>}}" id="tab-@(teamVenueInfo.TeamId)" role="tabpanel">
<div class="tab-pane@{if (Model.TeamUserRoundInfos.Exists(tvr => tvr.TeamId == Model.ActiveTeamId)){<text> show active</text>}}" id="tab-@(teamVenueInfo.TeamId)" role="tabpanel">
<div class="card pb-2 mb-3">
<div class="card-header px-2 py-1">
<div class="d-flex justify-content-between align-items-baseline">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ public string CompleteNameWithNickName
public bool IsPlayer => PlayerInTeams.Any();

[XmlIgnore]
public bool DataCompleteAsManager => (new[] {FirstName, LastName, PhoneNumber, Email}).All(s => !string.IsNullOrWhiteSpace(s));
public bool DataCompleteAsManager => (new List<string> {FirstName, LastName, PhoneNumber, Email}).TrueForAll(s => !string.IsNullOrWhiteSpace(s));

[XmlIgnore]
public bool DataCompleteAsPerson => (new[] { FirstName, LastName, Email }).All(s => !string.IsNullOrWhiteSpace(s));
public bool DataCompleteAsPerson => (new List<string> { FirstName, LastName, Email }).TrueForAll(s => !string.IsNullOrWhiteSpace(s));

protected override void OnSetValue(int fieldIndex, object valueToSet, out bool cancel)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public string GetPersistentFieldName(IEntityField2 field)
/// <returns>Returns the source table name an <see cref="IEntity2"/> belongs to in the persistent storage.</returns>
public string GetPersistentTableName(IEntity2 entity)
{
var i = GetFieldPersistenceInfo(entity.PrimaryKeyFields.First());
var i = GetFieldPersistenceInfo(entity.PrimaryKeyFields[0]);
return i.SourceObjectName;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,6 @@ static string Sanitize(string name)

using var da = _dbContext.GetNewAdapter();
var teamNames = await da.FetchQueryAsync<string>(new QueryFactory().Create().Select(() => TeamFields.Name.ToValue<string>()).Where(TeamFields.Id != teamEntity.Id), cancellationToken);
return teamNames.FirstOrDefault(tn => Sanitize(tn).Equals(Sanitize(teamEntity.Name)));
return teamNames.Find(tn => Sanitize(tn).Equals(Sanitize(teamEntity.Name)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ async Task<FactResult> FactResult(CancellationToken cancellationToken)
? (await Data.TenantContext.DbContext.AppDb.VenueRepository.GetOccupyingMatchesAsync(
Model.VenueId.Value, new DateTimePeriod(Model.PlannedStart, Model.PlannedEnd),
Data.TenantContext.TournamentContext.MatchPlanTournamentId, cancellationToken))
.FirstOrDefault(m => m.Id != Model.Id)
.Find(m => m.Id != Model.Id)
: null;

return new FactResult
Expand Down Expand Up @@ -146,8 +146,8 @@ async Task<FactResult> FactResult(CancellationToken cancellationToken)
if (!Model.VenueId.HasValue || !Model.PlannedStart.HasValue) return _successResult;
await LoadTeamsInMatch(cancellationToken);

var homeTeam = _teamsInMatch.FirstOrDefault(m => m.Id == Model.HomeTeamId);
var guestTeam = _teamsInMatch.FirstOrDefault(m => m.Id == Model.GuestTeamId);
var homeTeam = _teamsInMatch.Find(m => m.Id == Model.HomeTeamId);
var guestTeam = _teamsInMatch.Find(m => m.Id == Model.GuestTeamId);
var plannedStartDayOfWeek = (int?) Model.PlannedStart.Value.DayOfWeek;

if (homeTeam?.MatchDayOfWeek == null || guestTeam?.MatchDayOfWeek == null) return _successResult;
Expand Down Expand Up @@ -213,7 +213,7 @@ async Task<FactResult> FactResult(CancellationToken cancellationToken)
{
Message = string.Format(FixtureValidatorResource.ResourceManager.GetString(
nameof(FactId.PlannedStartTeamsAreNotBusy)) ?? string.Empty,
Data.PlannedMatch.HomeTeamId == busyTeams.First()
Data.PlannedMatch.HomeTeamId == busyTeams[0]
? Data.PlannedMatch.HomeTeamNameForRound
: Data.PlannedMatch.GuestTeamNameForRound),
Success = busyTeams.Length == 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ Task<FactResult> FactResult()

if (Data.Rules.MatchRule.BestOf && Data.Rules.MatchRule.MaxNumOfSets() == Model.Count)
{
factResult.Success = Model.Last().IsTieBreak;
factResult.Success = Model[^1].IsTieBreak;
}

return Task.FromResult(factResult);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ private Fact<FactId> AddressFieldsAreSet()
new FactResult
{
Message = VenueValidatorResource.AddressFieldsAreSet,
Success = new[] {Model.PostalCode, Model.City, Model.Street}.All(f => !string.IsNullOrWhiteSpace(f))
Success = new List<string> {Model.PostalCode, Model.City, Model.Street}.TrueForAll(f => !string.IsNullOrWhiteSpace(f))
})
};
}
Expand Down
Loading

0 comments on commit 555201e

Please sign in to comment.