【问题标题】:Will Linq ToList() generate NEW items?C#:Linq toList() 会生成新项目吗?
【发布时间】:2020-07-28 09:44:48
【问题描述】:

我有一个这样的列表:

  List<Food> foods = new List<Food>();
  foods.add(food1);
  foods.add(food2);
  foods.add(food3);
  ....

  foodsNewList = foods.Where("some conditions").ToList();

我想知道.ToList() 是否会生成NEW 项? 我的意思是对列表中以前项目的引用是否仍会保存? 例如。如果我有

food1.Name="test";

是否会导致foodsNewList中的食物更新?

【问题讨论】:

  • 它将更新该列表和该项目。
  • 您可以自己轻松地进行实验。列表中的元素是相同的对象,编译器通常无法知道如何复制它们。
  • 取决于Food 是类还是结构。它应该是一个类。
  • @HenkHolterman 如果是类会发生什么?
  • @HenkHolterman 在结构中,它们将被按值传递,它们将是新的副本。我说的对吗?

标签: c# list linq tolist


【解决方案1】:

如果在您的情况下它们是诸如“食物”之类的类列表,那么它们将是参考。您可以使用这样的简单控制台应用程序进行测试:

    static void Main(string[] args)
    {
        var foodList = new List<Food>
        {
            new Food { Id = 1, Name = "Peach" },
            new Food { Id = 2, Name = "Pear" },
            new Food { Id = 3, Name = "Apple" },
            new Food { Id = 4, Name = "Garlic" },
        };

        var message1 = "entries in foodList: ";
        var message2 = "entries in myNewFoodList: ";

        ShowEntries(message1, foodList);

        //Create new list with references
        var myNewFoodList = foodList.Where(x => x.Id > 1).ToList();

        ShowEntries(message2, myNewFoodList);

        //Update original list item that was also included in the new list
        foodList[1].Id = 7;
        foodList[1].Name = "Pineapple";

        ShowEntries(message1, foodList);
        ShowEntries(message2, myNewFoodList);

        Console.ReadLine();
    }

    public static void ShowEntries(string message, IList<Food> listOfFoods)
    {
        Console.WriteLine(message);
        foreach (var item in listOfFoods)
        {
            Console.WriteLine("Id: " + item.Id + ", Name: " + item.Name);
        }

        Console.WriteLine();
    }

    class Food
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

结果显示原始列表中的更新项目在新列表中也显示为更新:

【讨论】:

    【解决方案2】:

    foodsNewList 将只有这些Food 对象的引用/指针。更改 Food 对象将在列表中“更新”它们

    【讨论】:

    • ...假设Food 是一个类,而不是一个结构,当然
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多