1

I'm using postgresql as a database and I have a column called mealsIds it's type is array of integers.

I'm making the following SQL query.

        // Specify connection
        NpgsqlConnection conn = new NpgsqlConnection(
            "Server=127.0.0.1;" +
            "User Id=username;" +
            "Password=password;" +
            "Database=db;" +
            "Port=3500");
        conn.Open();

        // Define a query
        NpgsqlCommand cmd = new NpgsqlCommand($"SELECT catsids FROM restaurants WHERE id = {Properties.Settings.Default.ResId.ToString()}", conn);

        // Execute a query
        NpgsqlDataReader dr = cmd.ExecuteReader();

        if (dr.Read())
        {

            /*

           I WANT TO INSERT CODE HERE

            */

        }

        // Close connection
        conn.Close();

now I know that the result is an array of integers, and I want to store it in an array so I can use the values in it.

any idea how to do that??

2 Answers 2

1

There is a direct mapping from PG array to C# array. You can simply cast the returned object to an array

        int[] result;

        if (dr.Read())
        {
            result = (int[])dr.GetValue(0);
        }
Sign up to request clarification or add additional context in comments.

Comments

1

Try something like this:

List<int> myList = new List<int>();
while(dr.Read())
    {

        int newInt = int.Parse(dr["catsids"].ToString());
        //push to list or array here e.g. 
        myList.Add(newInt);

    }    

5 Comments

I'm getting this exception Can't cast database type integer[] to Int32
and what if try to parse int from strings? int.Parse(dr["catsids"].ToString()) @JohnSmith
no it won't work, you see the result is on field and it's value is this [1,2,3,4]
The dirty solution may look like dr["catsids"].ToString().Replace("[",string.Empty).Replace("]", string.Empty).Split(",").Select(s => int.Parse(s)).ToArray();
thank you very much for trying so hard to solve my problem, but I'm sorry it didn't work, appreciate it bro

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.