Reputation: 93
I have a chunk of code I know can be done better, I just am not sure how to go about it. I think there are some methods that can help with this but I am not sure so please forgive me if this is elemental programming.
I am iterating through a a DataReader to populate a List of objects, but I want to limit the number of indexes in the list. My current code looks like this:
while (dr.Read())
{
temp.Add(new Object()
{
PropertyA = dr.GetString(0),
...
...
});
}
if (temp.Count > 100)
{
for (int i = 0; i <= 100; i++)
{
retObject.Add(new Object()
{
PropertyA = temp[i].PropertyA,
...
...
});
}
return retObject;
}
else
{
return temp;
}
This essentially loops twice over a data set ... So, without sounding TOO much like a Novice programmer here, what would be the best way to limit the result set to 100 WITHOUT using TOP(###) in the Query itself? (We use Stored Procs so changing the Query is out of the question).
Thank folks! I look forward to your answers.
Upvotes: 1
Views: 98
Reputation: 564403
In your first loop, just keep a counter:
int found = 0;
while (dr.Read() && found < 100)
{
++found;
retObject.Add(new Object() // No need for "temp" anymore
{
PropertyA = dr.GetString(0),
...
...
});
}
return retObject;
Upvotes: 3