title | description | keywords | author | manager | ms.author | ms.date | ms.topic | ms.prod | ms.technology | ms.devlang | ms.assetid |
---|---|---|---|---|---|---|---|---|---|---|---|
Group results by contiguous keys |
How to group results by contiguous keys. |
.NET, .NET Core, C# |
stevehoag |
wpickett |
wiwagn |
12/1/2016 |
article |
.net-core |
.net-core-technologies |
dotnet |
cbda9c08-151b-4c9e-82f7-c3d7f3dac66b |
The following example shows how to group elements into chunks that represent subsequences of contiguous keys. For example, assume that you are given the following sequence of key-value pairs:
Key | Value |
---|---|
A | We |
A | think |
A | that |
B | Linq |
C | is |
A | really |
B | cool |
B | ! |
The following groups will be created in this order:
-
We, think, that
-
Linq
-
is
-
really
-
cool, !
The solution is implemented as an extension method that is thread-safe and that returns its results in a streaming manner. In other words, it produces its groups as it moves through the source sequence. Unlike the group
or orderby
operators, it can begin returning groups to the caller before all of the sequence has been read.
Thread-safety is accomplished by making a copy of each group or chunk as the source sequence is iterated, as explained in the source code comments. If the source sequence has a large sequence of contiguous items, the common language runtime may throw an xref:System.OutOfMemoryException.
The following example shows both the extension method and the client code that uses it.
[!code-cscscsrefContiguousGroups#1]
To use the extension method in your project, copy the MyExtensions
static class to a new or existing source code file and if it is required, add a using
directive for the namespace where it is located.