首页 新闻 赞助 找找看

数组类型问题

0
悬赏园豆:5 [已解决问题] 解决于 2009-06-16 14:26

假如有个fccom.xml文件!用循环把LIST读取出来。

ArrayList l = new ArrayList();

XDocument doc = XDocument.Load("fccom.xml");
            var list = (from node in doc.Root.Descendants("FcCom")
                        //where node.Attribute("id").Value == id
                        select new
                        {
                            scompany=node.Attribute("scompany").Value,
                            id=node.Attribute("id").Value
                        }).Take(12);
            foreach (var attr in list)
            {

       l.add(attr.toString());
            }

请问在这循环中我应该用什么来存放attr好呢!像我用ArrayList 来存放,可返回的值却是System.Collections.ArrayList这种类型的。

LoveO(∩_∩)O的主页 LoveO(∩_∩)O | 初学一级 | 园豆:55
提问于:2009-06-15 16:48
< >
分享
最佳答案
0

建议使用List<string>代替ArrayList类型,这样你获取l[0]的时候,返回的就是string类型了。

另外你也可以使用转换的方式将ArrayList内保存的项转换为string类型,比如这样:TextBox1.Text=l[0] as string;

还有你在概念上有点混淆,ArrayList是一个集合类,你说返回的是System.Collections.ArrayList,那说明你直接将集合返回了,你需要使用的时候应该是用集合内的项,比如像这样通过索引器访问其中的项:l[3],这样的返回值类型应该是Object类型。

你所说的“我试了 如果我写list<string> 那就又是另种类型”,肯定也是你直接把List<string>用作输出了。

完整代码:

List<string> l = new List<string>();

XDocument doc = XDocument.Load("fccom.xml");
            var list = (from node in doc.Root.Descendants("FcCom")
                        //where node.Attribute("id").Value == id
                        select new
                        {
                            scompany=node.Attribute("scompany").Value,
                            id=node.Attribute("id").Value
                        }).Take(12);
            foreach (var attr in list)
            {

       l.add(attr.toString());
            }

输出各项内容:

for(int i=0;i<l.Length;i++)

{

  Console.WriteLine(l[i]);

}

或者:

foreach(var f in l)

{

  Console.WriteLine(f);

}

虽然以上代码可以保证你正常输出获取的所有项,但是输出内容可能都是“System.Object”之类的,这是因为你select new取回的是匿名类型,它必然没有重写ToString()方法,所以没法输出你想要的信息,尝试将获取部分如下修改:

List<string> l = new List<string>();

XDocument doc = XDocument.Load("fccom.xml");
            var list = (from node in doc.Root.Descendants("FcCom")
                        //where node.Attribute("id").Value == id
                        select node.Attribute("scompany").Value).Take(12);
            foreach (var attr in list)
            {

       l.add(attr.toString());
            }

或者定义一个类型用于装载你要获取的数据

斯克迪亚 | 老鸟四级 |园豆:4124 | 2009-06-15 21:38
其他回答(3)
0

用List<>这个应该可以

懒懒メ虫 | 园豆:205 (菜鸟二级) | 2009-06-15 16:52
0

“用ArrayList 来存放,可返回的值却是System.Collections.ArrayList这种类型的”没看明白这句什么意思,用ArrayList 来存放,返回的是System.Collections.ArrayList,这有什么问题吗?

“如果我写list<string> 那就又是另种类型”,是什么类型?楼主主要想表达什么意思?

用List<string>应该是可以的。

麒麟.NET | 园豆:3614 (老鸟四级) | 2009-06-15 17:09
0

你的attr似乎是一个匿名类型,其ToString()方法返回的应该是个几乎不是人看的类型名称啊,你想要做什么?

Gray Zhang | 园豆:17610 (专家六级) | 2009-06-15 19:00
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册