开发者

I want to get the single value from a arraylist in a string

public ArrayList ChequeACpayee(string Payee, DateTime Date)
{
    ArrayList arr = new ArrayList();
    try
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("ViewChequeforAcPayee", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter p = new SqlParameter();
        p = cmd.Parameters.AddWithValue("@PayeeName", Payee);
        p = cmd.Parameters.AddWithValue("@Date", Date);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            ChequeInfo infoCheque = new ChequeInfo();

            infoCheque.AcPayee = dr["AcPayee"].ToString();

            arr.Add(infoCheque);
        }

        dr.Close();
        con.Close();
    }
    catch (Exception e)
    {
    }
    return arr;
}
Ar开发者_JAVA技巧rayList ArrAcpayee = ChequeAcPayee.ChequeACpayee (DDLPayee.SelectedItem.ToString(), BDPSelectDate.SelectedDate);

How do I get the single value from this arraylist? The value must be a converted to a string.


You could just use the indexer and a cast:

string payee = (string) ArrAcpayee[0];

But you should probably check the size first:

if (ArrAcpayee.Length != 1)
{
    // Create your own more appropriate exception
    throw new SomethingWentWrongException("Expected 1 payee entry; got "
                                          + ArrAcpayee.Length);
}
string payee = (string) ArrAcpayee[0];

However, I'm concerned about other aspects of your code:

  • Is there some reason you're not using generics? Are you really using .NET 1.1, or some framework which doesn't support List<T>?
  • Do you ever expect there to be more than one result, within the ChequeACpayee method? If not, that method should return a string and throw if there isn't exactly one result
  • Catching an exception and just swallowing it is a really bad idea. Do you really want to keep going as if nothing had gone wrong whatever happens?
  • You should use using statements to close your database connection and data reader, instead of calling Close() manually. Otherwise if an exception is thrown, you'll leak the connection.
  • Conventionally, parameters are camelCased, not PascalCased. (Local variables are invisible from outside the class, so less of an issue, but they're generally camelCased too.)


Assuming you're using linq:

ArrayList ArrAcpayee = ChequeAcPayee.ChequeACpayee (DDLPayee.SelectedItem.ToString(), BDPSelectDate.SelectedDate);

return ArrAcpayee.Cast<string>().Single(); //If there will always be just one value in the array list

return ArrAcpayee.Cast<string>().SingleOrDefault(); //If there will be either one or no value in the array list

return ArrAcpayee.Cast<string>().First(); //If you want to return the first value

Hope this helps


There are some build in methods in SqlDataReader that enables you to do that:

dr.GetString(dr.GetOrdinal("AcPayee"));

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜