我想从表中检索列的所有值 [英] i want to retrive all values of a column from a table
问题描述
List<object> arr = new List<object>();
foreach (Object item in ds.Tables[0].Columns)
{
arr.Add(item);
}
不知道它是否返回表的所有列值,如果是,那么如何将这些值取在int的数组中,或者字符串
don't know whether it returns all the column values of a table or not ,if yes then how to take these values in array of int ,or string
推荐答案
我认为这不符合您的要求或期望。
该代码在DataTable的列中运行 - 因此它添加到List中的对象是DataColumns,它们本身并没有很多用途,因为它们不包含从数据库中读取的值,但描述列包含的值的类型。
可能你想要的是行,而不是行中的值。
试试这个:
I don't think that does what you want, or expect.
That code runs through the Columns of a DataTable - so the objects it adds to your List are DataColumns, which aren;t a lot of use on their own, because they do not contain values read from the database, but descriptions of what type of values the column contains.
Probably what you want are the Rows instead, or more likely the values from the rows.
Try this:
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
{
Console.Write("{0} ", row[col]);
}
Console.WriteLine();
}
你应该明白我的意思。
BTW:创建一个<$ c $是个坏主意c>列出< object> - 使用 List< T>
而不是过时的 ArrayList的整个想法
是强类型的 - 它不会接受任何旧值,但只需要为其创建的特定类型。这意味着可以在编译时找到许多错误,而不是等到用户在运行时找到它们!
And you should see what I mean.
BTW: it is a poor idea to create a List<object>
at all - the whole idea of using a List<T>
instead of the outdated ArrayList
is that it is strongly typed - it will not accept "any old value" but expects only the specific type you create it for. This means that many faults can be found at compile time, instead of waiting until the user finds them at run time!
这篇关于我想从表中检索列的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!