【问题标题】:Change an object in a list of objects by using foreach over a smaller list of the same objects通过在较小的相同对象列表上使用 foreach 来更改对象列表中的对象
【发布时间】:2020-11-01 17:21:35
【问题描述】:

我正在尝试使用 foreach 循环来更改该列表中对象的值。但是,我需要一个不会更改的列表来枚举,并且在我这样做时要更改主列表。无论我尝试什么,我都会遇到错误,因为它正在更改我正在枚举的列表中的对象。

public static void GetHtml(Site website)
    {
        IEnumerable<Page> pages = new List<Page>();
        pages = website.PageList.Where(c => !c.Checked);
        WebClient client = new WebClient();
        foreach (Page page in pages)
        {
            try
            {
                page.Html = client.DownloadString(page.PageUrl);
                ParseHtml(page);
                ParseLinks(page, website);
                page.Valid = true;
                page.Checked = true;
            }
            catch
            {
                page.Valid = false;
                page.Checked = true;
            }
        }
    }

站点对象包含一个列表,我想在其中修改页面对象的值,但我不需要修改正在枚举的页面列表。我认为实例化一个新列表可以完成这项工作,但显然不是。

【问题讨论】:

  • 那么,您想要一个包含对象副本的新列表吗?如果是这样:您需要复制对象。

标签: c# foreach pass-by-reference ienumerable pass-by-value


【解决方案1】:

试试这段代码,ToList() 方法会创建一个你想要的新列表

public static void GetHtml(Site website)
{
    // you don't need to instantiate a new List, because the after the next statement the variable pages will hold a different object
    // and the List you created will be garbage
    IEnumerable<Page> pages;
    // the .ToList() will instantiate a new List with all the results of the Where
    pages = website.PageList.Where(c => !c.Checked).ToList();
    WebClient client = new WebClient();
    foreach (Page page in pages)
    {
        try
        {
            page.Html = client.DownloadString(page.PageUrl);
            ParseHtml(page);
            ParseLinks(page, website);
            page.Valid = true;
            page.Checked = true;
        }
        catch
        {
            page.Valid = false;
            page.Checked = true;
        }
    }
}

【讨论】:

  • 谢谢,这似乎适用于小规模测试。我担心它会引用一个新的 Page 对象,但它似乎改变了正确的对象。谢谢:)
猜你喜欢
  • 2017-06-14
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
  • 2015-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多