I'm reading denormalized data with a SqlDataReader
, the data has this form:
SELECT
Objects.ObjectName, Objects.OwnerId, Owners.Name
FROM
Objects
INNER JOIN Owners ON Objects.OwnerId = Owners.OwnerId
ORDER BY
Objects.OwnerId
Which has this output:
OjectName OwnerId OwnerName
Foo 1 Mr. Fu
Bar 1 Mr. Fu
Baz 2 Mrs. Daz
My reading loop is this:
using( SqlDataReader rdr = cmd.ExecuteReader() )
{
Int64 lastOwnerId = -1;
List<String> objectNames = new List<String>();
while( rdr.Read() )
{
String objName = rdr.GetString( 0 );
Int64 ownerId = rdr.GetInt64 ( 1 );
String ownerName = rdr.GetString( 2 );
if( ownerId != lastOwnerId && objectNames.Count > 0 )
{
// logic to populate and yield-return new Owner w/ ObjectNames
objectNames.Clear();
lastOwnerId = ownerId;
}
else
{
objectNames.Add( objName );
}
}
if( ownerId != lastOwnerId && objectNames.Count > 0 )
{
// logic to populate and yield-return new Owner w/ ObjectNames
}
}
The logic to populate and yield-return new Owner
w/ObjectNames
exists twice. Short of moving it to its own function, is there another loop pattern that is DRY?