Метод Add
Метод Add класса
ImmutableList<T>
не меняет текущий список, а возвращает новый
с элементом в конце.
Синтаксис
ImmutableList<T> newer = list.Add(item);
Пример
Давайте добавим элемент и сохраним старый список:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
class Program
{
static void Main()
{
ImmutableList<int> nums = ImmutableList.Create(1, 2, 3, 4, 5);
ImmutableList<int> nums2 = nums.Add(6);
Console.WriteLine(nums.Count);
Console.WriteLine(nums2.Count);
}
}
Результат выполнения кода:
5
6
Пример
Давайте начать с Empty:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
class Program
{
static void Main()
{
ImmutableList<int> a = ImmutableList<int>.Empty;
ImmutableList<int> b = a.Add(1);
Console.WriteLine(a.IsEmpty);
Console.WriteLine(b[0]);
}
}
Результат выполнения кода:
True
1
Пример
Давайте добавить строку:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
class Program
{
static void Main()
{
ImmutableList<string> items = ImmutableList.Create("a", "b", "c", "d", "e");
ImmutableList<string> items2 = items.Add("f");
Console.WriteLine(items2[5]);
}
}
Результат выполнения кода:
"f"
Пример
Давайте вывести оба списка:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
class Program
{
static void Main()
{
ImmutableList<int> nums = ImmutableList.Create(1, 2, 3);
ImmutableList<int> nums2 = nums.Add(4);
Console.WriteLine(string.Join(" ", nums));
Console.WriteLine(string.Join(" ", nums2));
}
}
Результат выполнения кода:
1 2 3
1 2 3 4
Смотрите также
-
метод
Add,
который дописывает в изменяемый List -
метод
ToBuilder,
который копит правки в builder -
класс
ImmutableList,
который остаётся неизменным -
метод
Add,
который добавляет в immutable массив