【问题标题】:Why will this loop not work with this class that I made?为什么这个循环不适用于我制作的这个类?
【发布时间】: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&lt;int&gt;
  • ID 来自私有 void UpdateOrganization(int LicensingKey, int ID){ ... }
  • 如果我正确理解您的问题,这确实应该是一个SELECT TOP(1) 1 FROM dbo.License WHERE OrgId = @id SQL 语句,您应该只使用SqlCommand.ExecuteScalar 获取常量值,如果不存在则返回null。这将消除您拥有的大部分代码。

标签: c# sql arrays visual-studio class


【解决方案1】:

问题是您将类对象本身与整数进行比较:

for (int n = 0; n < AllOrgs.Length; n++)
{
       if (AllOrgs[n].Equals(ID) == true) 
       {
            Found = 1;
       }
}

这里

if (AllOrgs[n].Equals(ID) == true) 

您需要将ID 与对象内部的integer (ListOfOrgs) 进行比较:

if (AllOrgs[n].ListOfOrgs == ID) 

if (AllOrgs[n].ListOfOrgs.Equals(ID)) 

您可以通过覆盖AlreadyMade 中的Equals 方法来归档它:

public class AlreadyMade
{
    public int ListOfOrgs { get; set; }

    public override bool Equals(object obj)
    {
        var item = (int?)obj;

        if (item == null)
        {
            return false;
        }

        return this.ListOfOrgs.Equals(item.Value);
    }
}

现在,当您将 (Equals) objectID 进行比较时,您将执行此方法。

【讨论】:

  • 啊啊啊我明白了!谢谢!
【解决方案2】:
if( AllOrgs.OfType<AlreadyMade>().ToList().Contains ( new AlreadyMade {ListOfOrgs = ID}) == true)

试试上面的代码,不需要for循环。很抱歉频繁编辑,但由于您的命名约定,我感到困惑。

【讨论】:

    猜你喜欢
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 2013-12-13
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多