John
John

Reputation: 487

How can I read string value and store it in a array using data reader

I am reading some list of values in the result but I am not sure where I am going wrong, I wont know the array size so I cant assign any value to it

string[] result = null;
while (reader.Read())
{
    result = Convert.ToString[](reader["RoleID"]);
}
reader.Close();

I am getting: Syntax error; value expected.

After I get the result value, how can I compare the values inside the result with a string? For example, I want to check whether the string check="Can send message"; is present in the result array or not. How can I do that?

Upvotes: 3

Views: 15666

Answers (4)

Mopthe
Mopthe

Reputation: 1

The list in Anthony Pegram's example can easily be converted to an array if needed.

string[] result = results.ToArray();

Upvotes: 0

Anthony Pegram
Anthony Pegram

Reputation: 126834

Your code is syntactically wrong, hence the error. But when you have to build a collection of items but you do not know the size in advance, you want to use a List<T> as opposed to an array. The list will allow you to keep adding items.

var results = new List<string>();
while (reader.Read())
{
    results.Add(reader["RoleID"].ToString());
}

// results now holds all of the RoleID values in the reader 

You can access the elements of the list via index, just like an array, and can query the list using Linq (also just like an array) if needed.

string check = "something";
if (results.Any(item => item.Equals(check)))
{
    // results contains the value in check 
}

// or use all items that equal check
foreach (var item in results.Where(obj => obj.Equals(check))
{
    // do something with each item that equals check
}

Upvotes: 3

james lewis
james lewis

Reputation: 2532

You should use a list as follows:

var results = new List<string>();
while( reader.Read() ){
    results.Add(reader["RoleID"].ToString());
}

Then you would iterate through all the strings in the collection and check them using a foreach statement:

foreach(var result in results) {
    if(result == "check") {
        // do something
    }
}

Upvotes: 0

huMpty duMpty
huMpty duMpty

Reputation: 14460

I preffer using ArrayList

var result= new ArrayList();
while (reader.Read())
        {
            result.Add(Convert.ToString[](reader["RoleID"]));
        }reader.Close();

Upvotes: 1

Related Questions