Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 750
John Avatar asked Apr 27 '26 19:04

John


2 Answers

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
}
like image 129
Anthony Pegram Avatar answered Apr 30 '26 10:04

Anthony Pegram


I preffer using ArrayList

var result= new ArrayList();
while (reader.Read())
        {
            result.Add(Convert.ToString[](reader["RoleID"]));
        }reader.Close();
like image 37
huMpty duMpty Avatar answered Apr 30 '26 11:04

huMpty duMpty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!