Skip to content

Commit f89c80f

Browse files
committed
SearchAllNestedTypesRecursively now accepts an order by predicate and uses FirstOrDefault instead of SingleOrDefault when returning a possible match.
1 parent b22769b commit f89c80f

1 file changed

Lines changed: 14 additions & 4 deletions

File tree

XObjectsCode/Extensions/CodeDomExtensions.cs

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -482,23 +482,33 @@ public static List<CodeTypeDeclaration> FlattenAllNestedTypesRecursively(this Co
482482

483483
/// <summary>
484484
/// Searches for a nested type with the specified name within the current <see cref="CodeTypeDeclaration"/>
485-
/// and all its nested types recursively.
485+
/// and all its nested types recursively. Uses the LINQ method <see cref="Enumerable.FirstOrDefault{TSource}(IEnumerable{TSource})"/> to
486+
/// return the possible match.
486487
/// </summary>
487488
/// <param name="type">The current type.</param>
488489
/// <param name="predicate">A searching predicate</param>
490+
/// <param name="orderByPredicate">Pass another predicate to order the results if you anticipate <paramref name="predicate"/> will return more than one
491+
/// result.</param>
489492
/// <returns>
490493
/// The <see cref="CodeTypeMember"/> representing the nested type with the specified name,
491494
/// or <c>null</c> if no such type is found.
492495
/// </returns>
493-
public static CodeTypeMember? SearchAllNestedTypesRecursively(this CodeTypeDeclaration type, Func<CodeTypeMember, bool> predicate)
496+
public static CodeTypeMember? SearchAllNestedTypesRecursively(this CodeTypeDeclaration type, Func<CodeTypeMember, bool> predicate,
497+
Func<CodeTypeMember, bool>? orderByPredicate = null)
494498
{
495499
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
496500

497-
var thePossibleType = type.Members.Cast<CodeTypeMember>().SingleOrDefault(predicate);
501+
CodeTypeMember? thePossibleType = null;
502+
IEnumerable<CodeTypeMember> candidates = type.Members.Cast<CodeTypeMember>().Where(predicate);
503+
if (orderByPredicate is not null) {
504+
candidates = candidates.OrderByDescending(orderByPredicate);
505+
}
506+
thePossibleType = candidates.FirstOrDefault();
507+
498508
if (thePossibleType is null) {
499509
IEnumerable<CodeTypeDeclaration> nestedTypes = type.Members.OfType<CodeTypeDeclaration>();
500510
foreach (var nestedType in nestedTypes) {
501-
thePossibleType = nestedType.SearchAllNestedTypesRecursively(predicate);
511+
thePossibleType = nestedType.SearchAllNestedTypesRecursively(predicate, orderByPredicate);
502512
if (thePossibleType is not null) break;
503513
}
504514
}

0 commit comments

Comments
 (0)