2011-05-18 49 views
2

可能重复:
How can I easily convert DataReader to List<T>?如何将DataReader中的值放入列表<T>?

我希望把它从DataReader对象来在通用列表中的数据。我做了这样的,但它不工作...

我在foreach行得到抛出异常错误!

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; 
     } 
    } 
} 
+0

可能从这里[link](http://stackoverflow.com/questions/1464883/how-can-i-easily-convert-datareader-to-listt) – Dotnet 2011-05-18 09:26:13

+0

请将您的变量名称重命名为英文 - 写 – abatishchev 2011-05-18 09:40:32

+0

我已编辑abatishchev – PsyGnosis 2011-05-18 10:06:33

回答

8

无法以您所描述的方式访问SqlDataReader,因为它没有实现IEnumerable。相反,你需要单独访问每个字段:

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 
     } 
    } 
} 

如果你只选择一列,并确信它是一个整数,那么可以简化像这样的代码:

SqlDataReader puanoku = cmd2.ExecuteReader(); 
List<int> puann = new List<int>(); 
while (puanoku.Read()) 
{ 
    int value = puanoku.GetInt32(1); 

    // Do something with the int here... 
} 

article可能有些用处。

+0

我有一列,但列有多个值..我想检查eslesenpuan包含puan通用列表如果(puan.contains(eslesenpuan)) 我想更新该点.. – PsyGnosis 2011-05-18 10:01:32

3

我认为你需要从读取器中获得项目,如puanoku["item"]并将其转换为int。添加,然后只有你可以将它添加到列表中。

while(Reader.Read()) 
{ 
    var myId = (int)Reader["myId"]; 
    myIdList.Add(myId); // or you can do myIdList.Add(int)Reader["myId"]); 
} 
0

datareader是指向表中的行的指针。您可以使用阅读器上的索引器获取各个属性,并使用FieldCount属性获取这些值。

while (puanoku.Read()) 
{ 
    for(int i = 0; i < puanoku.FieldCount) 
    { 
     puann.Add(puanoku.GetInt32(i)); 
    } 
} 

如果你只是想你应该使用一个HashSet,而不是一个列表,因为它会为O测试存在(1),而不是O(n)的唯一值。

相关问题