简体   繁体   中英

Loop nested System.object[] C#

I've a variable of type Object and it contains data like this

Items[0]=[ {id=a,name=b,url=c},{id=d,name=e,url=f},{id=a,name=b,url=c}...]

Items[1]=[ {id=a,name=b,url=c},{id=d,name=e,url=f},{id=a,name=b,url=c}...]

.....

how can I loop this?

UPDATE

            if (null != myProjects) //myProjectsis of type object
            {
                dirEntry = myProjects as Dictionary<string, object>;
                dirDetails = dirEntry["Response"] as Dictionary<string, object>;
                object projects = null;
                foreach (var item in dirDetails)
                {
                    if ("Items" == item.Key)
                    {
                        projects = dirDetails["Items"];
                        break;
                    }
                }

now projects will contain object array. I wan't to loop that to get some values

You could follow this sample,

Class for project data(id, name, url)

public class ObjectList
{
    public ObjectList(string id1, string name1, string url1)
    {
        id = id1;
        name = name1;
        url = url1;
    }
    public string id { get; set; }
    public string name { get; set; }
    public string url { get; set; }
}

Class for array items(projects)

 public class RootObj
    {
        public string objectType { get; set; }
        public List<ObjectList> objectList { get; set; }
    }

Once you have got the object based array, here is the sample you can follow to loop through the projects.

private void ManipulateProjects()
{
    object[] projects = new object[5];

    RootObj item1Obj = new RootObj();
    List<ObjectList> item1List = new List<ObjectList>();
    item1List.Add(new ObjectList("1", "Rone1", "htt://google1.com"));
    item1List.Add(new ObjectList("2", "Rone2", "htt://google2.com"));
    item1List.Add(new ObjectList("3", "Rone3", "htt://google3.com"));
    item1Obj.objectList = item1List;
    projects[0] = item1Obj;

    RootObj item2Obj = new RootObj();
    List<ObjectList> item2List = new List<ObjectList>();
    item2List.Add(new ObjectList("10", "Rone10", "htt://google10.com"));
    item2List.Add(new ObjectList("12", "Rone12", "htt://google20.com"));
    item2List.Add(new ObjectList("13", "Rone13", "htt://google30.com"));
    item2Obj.objectList = item2List;
    projects[1] = item2Obj;

    //Once you have your formatted array of projects then it is just a matter of looping through it.
    foreach (RootObj item in projects)
    {
        if (item == null) continue;
        List<ObjectList> items = item.objectList;

        foreach (ObjectList item1 in items)
        {
            //Response.Write(item1.id + " " + item1.name + " " + item1.url + "<br />");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM