7
7
8
8
using System ;
9
9
using System . Collections . Generic ;
10
+ using System . Collections . Immutable ;
10
11
using Microsoft . CodeAnalysis ;
11
12
12
13
namespace CommunityToolkit . Mvvm . SourceGenerators . Extensions ;
@@ -16,6 +17,46 @@ namespace CommunityToolkit.Mvvm.SourceGenerators.Extensions;
16
17
/// </summary>
17
18
internal static class IncrementalValuesProviderExtensions
18
19
{
20
+ /// <summary>
21
+ /// Groups items in a given <see cref="IncrementalValuesProvider{TValue}"/> sequence by a specified key.
22
+ /// </summary>
23
+ /// <typeparam name="TLeft">The type of left items in each tuple.</typeparam>
24
+ /// <typeparam name="TRight">The type of right items in each tuple.</typeparam>
25
+ /// <param name="source">The input <see cref="IncrementalValuesProvider{TValues}"/> instance.</param>
26
+ /// <param name="comparer">A <typeparamref name="TLeft"/> comparer.</param>
27
+ /// <returns>An <see cref="IncrementalValuesProvider{TValues}"/> with the grouped results.</returns>
28
+ public static IncrementalValuesProvider < ( TLeft Left , ImmutableArray < TRight > Right ) > GroupBy < TLeft , TRight > (
29
+ this IncrementalValuesProvider < ( TLeft Left , TRight Right ) > source ,
30
+ IEqualityComparer < TLeft > comparer )
31
+ {
32
+ return source . Collect ( ) . SelectMany ( ( item , _ ) =>
33
+ {
34
+ Dictionary < TLeft , ImmutableArray < TRight > . Builder > map = new ( comparer ) ;
35
+
36
+ foreach ( ( TLeft hierarchy , TRight info ) in item )
37
+ {
38
+ if ( ! map . TryGetValue ( hierarchy , out ImmutableArray < TRight > . Builder builder ) )
39
+ {
40
+ builder = ImmutableArray . CreateBuilder < TRight > ( ) ;
41
+
42
+ map . Add ( hierarchy , builder ) ;
43
+ }
44
+
45
+ builder . Add ( info ) ;
46
+ }
47
+
48
+ ImmutableArray < ( TLeft Hierarchy , ImmutableArray < TRight > Properties ) > . Builder result =
49
+ ImmutableArray . CreateBuilder < ( TLeft , ImmutableArray < TRight > ) > ( ) ;
50
+
51
+ foreach ( KeyValuePair < TLeft , ImmutableArray < TRight > . Builder > entry in map )
52
+ {
53
+ result . Add ( ( entry . Key , entry . Value . ToImmutable ( ) ) ) ;
54
+ }
55
+
56
+ return result ;
57
+ } ) ;
58
+ }
59
+
19
60
/// <summary>
20
61
/// Creates a new <see cref="IncrementalValuesProvider{TValues}"/> instance with a gven pair of comparers.
21
62
/// </summary>
0 commit comments