如何以数组形式获取select查询的结果 [英] How to get result of select query in array form
本文介绍了如何以数组形式获取select查询的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望结果从tblRate中选择vmId,其中userId = 2为数组形式。
我尝试过:
从tblRate中选择vmId,其中userId = 2
解决方案
DataTable的行可以作为二维访问数组已经(有一些索引器),如dt.Rows [0] [column1]
,所以你可能不需要转换它,但是......
dt.Rows.Cast< DataRow>()。选择(r = > r.ItemArray)。 ToArray();
如下例所示,你必须尝试man。
public class ClassName
{
public string Col1 {get;组; }
public int Col2 {get;组; }
}
现在你可以使用循环填充列表和ToArray如果你真的需要一个数组:
ClassName [] allRecords = null;
string sql = @SELECT col1,col2
from some table;
using(var command = new SqlCommand(sql,con))
{
con.Open();
using(var reader = command.ExecuteReader())
{
var list = new List< ClassName>();
while(reader.Read())
list.Add(new ClassName {Col1 = reader.GetString(0),Col2 = reader.GetInt32(1)});
allRecords = list.ToArray();
}
}
您需要创建与查询结果列名相同属性的Model,并将结果分配给执行的查询文件查询。
例如:
查询:
从员工中选择* br $>
C#型号:
公共级员工{
public Employee_id;
public Employee_Name;
。
。
。
所以...
}
现在将Employee对象分配给查询结果。
希望它对您有所帮助,请不要忘记标记我的好评。 :)
I want the result "select vmId from tblRate where userId=2" into array form.
What I have tried:
select vmId from tblRate where userId=2
解决方案
Rows of DataTable can be accessed as a two dimensional array already (have some indexers for that), likedt.Rows[0]["column1"]
, so you probably need not convert it, but...
dt.Rows.Cast<DataRow>().Select(r => r.ItemArray).ToArray();
Like below example you have to try man.
public class ClassName { public string Col1 { get; set; } public int Col2 { get; set; } } Now you can use a loop to fill a list and ToArray if you really need an array: ClassName[] allRecords = null; string sql = @"SELECT col1,col2 FROM some table"; using (var command = new SqlCommand(sql, con)) { con.Open(); using (var reader = command.ExecuteReader()) { var list = new List<ClassName>(); while (reader.Read()) list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) }); allRecords = list.ToArray(); } }
You need to create Model with same attribute as column name of query result and assign result to that query file executing query.
For Example:
Query:
Select * from Employee
C# Model:
public class Employee{
public Employee_id;
public Employee_Name;
.
.
.
So on...
}
and now assign Employee object to result of query.
Hope it will helpful for you, please don't forget to mark my good rating. :)
这篇关于如何以数组形式获取select查询的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文