VSB
VSB

Reputation: 10375

Will Linq ToList() generate NEW items?

I have a list like this:

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

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

I want to know if .ToList() will generate NEW items or not? I mean is reference to previous items in list will be still saved or not? E.g. if I have

food1.Name="test";

Will it will cause update of a food in foodsNewList or not?

Upvotes: 0

Views: 66

Answers (2)

sr28
sr28

Reputation: 5106

If they're a list of classes like 'Food' in your case then they will be references. You can test this with a simple console app like this:

    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; }
    }

Results show that the updated item in the original list also is shown as updated in the new list:

enter image description here

Upvotes: 2

ToTheMax
ToTheMax

Reputation: 1031

foodsNewList will just have references/pointers to these Food objects. Changing a Food object will "update" them in the list

Upvotes: 2

Related Questions