【问题标题】:How to access arraylist?如何访问数组列表?
【发布时间】:2014-01-17 11:45:12
【问题描述】:

我有这样的列表方法 testing 是有theree的类

 public ArrayList converttolist(string commandText, CommandType commandType)
    {
        ArrayList Listlines = new ArrayList();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = commandText;
        cmd.CommandType = commandType;
        cmd.Connection = obj_con.getconection();
        try
        {

            cmd.Connection.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                testing ts = new testing();

                var alldata = new state_testingCLS.testing();

                while (sdr.Read())
                {
                    ts.id_11 = Convert.ToInt64(sdr["id_11"]);
                    ts.countryid = Convert.ToInt64(sdr["countryid"]);
                    ts.state = Convert.ToString(sdr["state"]);
                    Listlines.Add((ts));
                }
                sdr.Close();
            }

            return Listlines;

        }
        catch (Exception ex)
        {

            throw ex;
        }
        finally
        {
            cmd.Connection.Close();
            cmd.Dispose();

        }
    }

listlines 中,我必须获取记录,但我对此一无所知,请帮我解决这个问题

现在如果我访问它

ArrayList aa= cls.getAll();
                foreach (state_testingCLS.testing Txt in aa)
                {


                    string aa1 = Txt.state.ToString();

                }

每次返回相同的数据

【问题讨论】:

  • 检查更新的@NitinVarpe
  • 我不确定我是否理解您的问题,但您正在插入 alldata 但从未在其上设置任何属性。您的意思是插入ts 吗? (Listlines.Add(ts))
  • 抱歉是我的错误@ClaudioRedi

标签: c# list


【解决方案1】:

你可以创建单独的类

public class MyClass
{
  public Int64 id_11 { get; set; }
public Int64 countryid { get; set; }
public string state { get; set; }
}

在方法中

 Ilist<MyClass> myclassList=new List<MyClass>();

之后,您可以将字段分配给此类的新对象并将其添加到列表中

myclassList.Add(new MyClass(){
    id_11=ts.id_11,
    countryid =ts.countryid,
    state =ts.state
});

然后您可以将方法的返回类型更改为IList&lt;MyClass&gt;

更新

试试

for(int i = 0; i < aa.Length; i++)
{
       var obj=(testing)aa[i]
}

然后从 obj 中获取值

【讨论】:

  • 好的,我理解这个,但我的问题是如何获取这个,我为这个使用单独的方法,所以我不能将它与返回类型一起使用
  • 没有得到你,你不能在 Ilist 上使用循环
  • 但是我有一个方法会返回整个数组列表,然后我必须读取该数组列表
  • 我不知道你为什么卡在 ArrayList 检查这个链接上的第一个答案stackoverflow.com/questions/3367524/…
  • 我在Listlines 中有数据,但我无法访问它返回 null
猜你喜欢
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多