From 80ca30b448efb01e7375fe04cff3dc4574b1b994 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 13 May 2026 19:37:08 +0000 Subject: [PATCH] Refactor ForwardExcept with TFM-specialized TryGetNonEnumeratedCount Agent-Logs-Url: https://github.com/microsoft/agent-framework/sessions/b081f61f-93ce-45dc-abbd-82c465395470 Co-authored-by: lokitoth <6936551+lokitoth@users.noreply.github.com> --- .../WorkflowBuilderExtensions.cs | 20 +++++++------------ 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilderExtensions.cs b/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilderExtensions.cs index ae5625edcb..eeeaf63bc8 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilderExtensions.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilderExtensions.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; +using System.Linq; using Microsoft.Shared.Diagnostics; namespace Microsoft.Agents.AI.Workflows; @@ -112,26 +113,19 @@ public static class WorkflowBuilderExtensions Throw.IfNull(targets); Func predicate = WorkflowBuilder.CreateConditionFunc((Func)IsAllowedType)!; - List targetList = new(); - foreach (ExecutorBinding target in targets) - { - Throw.IfNull(target, nameof(targets)); - targetList.Add(target); + if (targets.TryGetNonEnumeratedCount(out int count) && count == 1) + { + return builder.AddEdge(source, Throw.IfNull(targets.First(), nameof(targets)), predicate); } - Throw.IfNullOrEmpty(targetList, nameof(targets)); - - if (targetList.Count == 1) - { - return builder.AddEdge(source, targetList[0], predicate); - } - - return builder.AddSwitch(source, (switch_) => switch_.AddCase(predicate, targetList)); + return builder.AddSwitch(source, (switch_) => switch_.AddCase(predicate, targets.Select(ValidateTarget))); // The reason we can check for "null" here is that CreateConditionFunc will do the correct unwrapping // logic for PortableValues. static bool IsAllowedType(object? message) => message is null; + + ExecutorBinding ValidateTarget(ExecutorBinding target) => Throw.IfNull(target, nameof(targets)); } ///