0

How can I return multiple values from a class in C# I tried in the below way but it didn't work for me.

protected static string setvalues;
public static string myfunction()
{
        cmd = new SqlCommand("SELECT * FROM category", con);
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            setvalues = dr[0].ToString();
        }
        con.Close();
        return setvalues.ToString();
}

I have the following in Categories table

Mobiles
Laptops
Cloths
DVD players
Televisions
Cameras

Anybody please help me in building a code that can return thousands of values.

1
  • You can't just return them as a string[] ? Or make it an ienumerable and use a yeild return. Commented Mar 11, 2012 at 4:29

3 Answers 3

4

You want to return a List<String> (or an IEnumerable<string> using an iterator with yield return)

Sign up to request clarification or add additional context in comments.

6 Comments

I am sorry, I never worked any of the above that you mention. Can you please provide me with its syntax?
Doesn't .net 3 or .net 4 have a built-in tuple type so that SELECT * can return Tuple<...>[]? That is, an array of tuples instead of a vector of strings?
List<string> myList = new List<string>(); myList.Add("a string"); then return the list.
@Bahamut - By trying your code I am getting output as 'System.Collections.Generic.List`1[System.String]'
to get the output from the list do a foreach. foreach(string strTemp in myList){ // do whatever to strTemp };
|
1

The List type in the C# language can solve above problem. With List, you do not need to manage the size on your own

    protected static List<string> listSetValues = new List<string>();
    public static List<string> myfunction()
    {
        cmd = new SqlCommand("SELECT * FROM category", con);
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            listSetValues.Add(dr[0].ToString());
        }
        con.Close();
        return listSetValues;
    }

2 Comments

I am getting output as System.Collections.Generic.List1[System.String]`
You can simply import System.Collections.Generic namespace and can have access to all properties and method of List......
0

Yes you can use Tuple class in .net 4.0. Forexample,

var population = new Tuple<string, int, int, int, int, int, int>(
                       "New York", 7891957, 7781984, 
                       7894862, 7071639, 7322564, 8008278);

OR
var population = Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278);

For more information about properties and functions of Tuple class, visit Tuple Class on MSDN

Comments

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.