Possible Duplicate:
How can I easily convert DataReader to List<T>?
I want to put the data 开发者_如何学JAVAwhich is coming from datareader object in a generic list. I have done like this but it doesn't work...
I am getting cast exception error in foreach row!
SqlDataReader pointreader = cmd2.ExecuteReader();
var pointt = new List<int>();
while (pointreader.Read())
{
foreach (int item in pointreader)
{
pointt.Add(item);
if (pointt.Contains(point))
{
matchpoint = item;
}
}
}
SqlDataReader cannot be accessed in the way you have described as it does not implement IEnumerable. Instead you need to access each field individually:
SqlDataReader puanoku = cmd2.ExecuteReader();
List<int> puann = new List<int>();
while (puanoku.Read())
{
for (int i = 0; i < puanoku.FieldCount; i++)
{
if (puanoku.GetFieldType(i) == typeof(int))
{
// Do something here
}
}
}
If you've only selected one column and are certain that it is an int then you can simplify the code like so:
SqlDataReader puanoku = cmd2.ExecuteReader();
List<int> puann = new List<int>();
while (puanoku.Read())
{
int value = puanoku.GetInt32(1);
// Do something with the int here...
}
This article may be of some use.
I think you need to get item from the Reader, like puanoku["item"]
and convert it to int. Add then only you can add it to the list.
while(Reader.Read())
{
var myId = (int)Reader["myId"];
myIdList.Add(myId); // or you can do myIdList.Add(int)Reader["myId"]);
}
The datareader is a pointer to rows in a table. You can get to the individual attributes using an indexer on the reader and use the FieldCount
property to obtain the values.
while (puanoku.Read())
{
for(int i = 0; i < puanoku.FieldCount)
{
puann.Add(puanoku.GetInt32(i));
}
}
If you only want unique values you should use a HashSet rather than a List since it will test for existence in O(1) rather than O(n).
精彩评论