Syntax value: return _ (); IEnumerable <TSource> _ ()
In the C # code below, I found the weird use of _() . Can anyone explain what this means?
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) { if (source == null) throw new ArgumentNullException(nameof(source)); if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); return _(); IEnumerable<TSource> _() { var knownKeys = new HashSet<TKey>(comparer); foreach (var element in source) { if (knownKeys.Add(keySelector(element))) yield return element; } } } +7
Anh lai
source share1 answer
The code can be more easily understood by inserting a line break after the return :
return _(); IEnumerable<TSource> _() { var knownKeys = new HashSet<TKey>(comparer); foreach (var element in source) { if (knownKeys.Add(keySelector(element))) yield return element; } } In this context, underscore is simply an arbitrary name for a local function (this is a new function introduced in C # 7.0). If you prefer, you can replace the underscore with a more descriptive name:
return DistinctByHelper(); IEnumerable<TSource> DistinctByHelper() { var knownKeys = new HashSet<TKey>(comparer); foreach (var element in source) { if (knownKeys.Add(keySelector(element))) yield return element; } } As a local function, the _ (or DistinctByHelper) method can access all the variables of the DistinctBy method.
By the way, the reason for having two methods here is that if any argument is null, an ArgumentNullException will be thrown right away when a DistinctBy is called instead of when the result is enumerated (due to the yield return ).
+9
Michael liu
source share