在foreach循环中编辑列表

时间:2009-09-28 12:41:31

标签: c# foreach ref

我有一个具有以下结构的对象:(伪代码)

class Client
{
- int ID
- int? ParentID
- string Name
- datetime CreateDate
- int ACClientID
- List <Client> Clients }

我想使用递归foreach遍历整个嵌套结构,将ALL的ACClientID设置为值。

我知道foreach中的枚举器是不可变的,因此以下内容不起作用:

 private static bool AssignToChildren(ref ATBusiness.Objects.Client client, int ACClientID)
        {
            client.ACClientID = ACClientID;

            foreach (ATBusiness.Objects.Client child in client.Clients)
            {
                AssignToChildren(ref child, ACClientID);
            }
        }

实现目标的最有效方法是什么?

PS:我不会在结构中添加或删除,只是为每个嵌套的Client对象设置一个属性。

[edit]我看过What is the best way to modify a list in a 'foreach' loop?,但它没有为我提供我需要的答案。

4 个答案:

答案 0 :(得分:11)

由于您从未分配参数client,因此无需使用ref传递参数。

由于您未自行修改List<T>对象,因此即使在枚举期间也无法修改ACCClientID属性。只有当你试图篡改枚举后面的列表成员资格时才会出现异常。

答案 1 :(得分:1)

    private static bool AssignToChildren(ATBusiness.Objects.Client client, int ACClientID)
    {
        client.ACClientID = ACClientID;

        foreach (ATBusiness.Objects.Client child in client.Clients)
        {
            AssignToChildren(child, ACClientID);
        }
    }

答案 2 :(得分:0)

我可以为此建议一个特定的属性吗?

class Client
{
    public Client()
    {
        Clients = new List<Client>();
    }

    public List<Client> Clients { get; private set; }

    private int aCClientID;

    public int ACClientID
    {
        get { return aCClientID; }
        set { aCClientID = value; }
    }

    public int ACClientIDRecursive
    {
        get
        {
            return aCClientID;
        }
        set
        {
            aCClientID = value;
            foreach (var c in Clients)
            {
                c.ACClientIDRecursive = value;
            }
        }
    }
}

答案 3 :(得分:-2)

试试这个:

private static bool AssignToChildren(ref ATBusiness.Objects.Client client, int ACClientID)
{
  client.ACClientID = ACClientID;
  for (int i = client.Clients.Count - 1; i >= 0; i--) 
  {
    AssignToChildren(ref client.Clients[i], ACClientID);
  }
}
相关问题