【发布时间】:2016-06-21 16:16:36
【问题描述】:
所以我做了这门课:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// Class for checking if an OrgID already exsists.
public class AlreadyMade
{
public int ListOfOrgs { get; set; }
}
我正在尝试从我在 SQL 数据库中拥有的表中的整数列创建一个数组,以便我可以使用该数组来查看该整数是否已经存在,这里是那段代码:
SqlConnection con = new SqlConnection(constr);
AlreadyMade[] AllOrgs = null;
string CheckQuery = @"SELECT OrgID FROM License";
using (var command = new SqlCommand(CheckQuery, con))
{
con.Open();
using (var reader = command.ExecuteReader())
{
var list = new List<AlreadyMade>();
while (reader.Read())
list.Add(new AlreadyMade {ListOfOrgs = reader.GetInt32(0)});
AllOrgs = list.ToArray();
}
}
for (int n = 0; n < AllOrgs.Length; n++)
{
if (AllOrgs[n].Equals(ID) == true)
{
Found = 1;
}
}
问题是它总是跳过
if (AllOrgs[n].Equals(ID) == true)
行我正在寻找的整数是否已经存在于数组中。很明显,我显然不明白我所做的课程是如何真正运作的,所以有人可以帮我弄清楚这一点,最好解释一下我做错了什么吗?谢谢!
【问题讨论】:
-
这个 ID 是从哪里来的?是参数吗?
-
在你的sql server上做过滤不是更好吗?
-
你为什么要使用
AlreadyMade而不仅仅是创建List<int>? -
ID 来自私有 void UpdateOrganization(int LicensingKey, int ID){ ... }
-
如果我正确理解您的问题,这确实应该是一个
SELECT TOP(1) 1 FROM dbo.License WHERE OrgId = @idSQL 语句,您应该只使用SqlCommand.ExecuteScalar获取常量值,如果不存在则返回null。这将消除您拥有的大部分代码。
标签: c# sql arrays visual-studio class