JDawg848 JDawg848 - 5 months ago 12
SQL Question

Why will this loop not work with this class that I made?

So I made this class:

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


I am trying to make an array from an integer column in a table that I have in an SQL database so that I can use that array to see if that integer already exists or not, and here is that bit of code:

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


The problem is that it always skips over the

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


line whether or not the integer I am looking for already exists in the array. It's obvious that I apparently don't understand how the class I made really works, so could someone please help me figure this one out and preferably explain what I am doing wrong? Thank you!

Answer

The problem is that you are comparing the class object itself with the integer:

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

Here

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

You need to compare ID with the integer inside the object (ListOfOrgs):

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

or

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

You could archive that by overriding the Equals method inside AlreadyMade:

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

Now when you compare (Equals) the object with the ID you will execute this method.

Comments