I was reading about the " with " expression on MSDN, and decided to tinker a bit with the sample code provided there. How do I append the list of tags when creating var copy , without writing out the three tags explicitly, like I did here ( new List<string> { "A", "B", "C"}
)? I tried Tags = original.Tags + "C"
, but that doesn't work, of course.
using System;
using System.Globalization;
using System.Threading.Tasks;
namespace AsyncBreakfast
{
public class ExampleWithReferenceType
{
public record TaggedNumber(int Number, List<string> Tags)
{
public string PrintTags() => string.Join(", ", Tags);
}
public static void Main()
{
var original = new TaggedNumber(1, new List<string> { "A", "B" });
var copy = original with { Tags = new List<string> { "A", "B", "C"} };
Console.WriteLine($"Tags of {nameof(copy)}: {copy.PrintTags()}");
// output: Tags of copy: A, B, C
original.Tags.Add("C");
Console.WriteLine($"Tags of {nameof(copy)}: {copy.PrintTags()}");
// output: Tags of copy: A, B, C
}
}
}
You can create a copy of a list, with an extra element, by doing something like:
with { Tags = original.Tags.Append("C").ToList() }
However, if you want your records to be immutable (and you probably should, if you're following the approach of doing modifications by creating a copy), then you probably don't want to be using a List<T>
at all, since List<T>
is mutable.
Instead, you can use an ImmutableList<T>
. This has an Add
method which returns a new ImmutableList<T>
containing the specified element, meaning you can write:
with { Tags = original.Tags.Add("C") }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.