Dodawanie elementów do List<T>
Jednym z najczęstszych scenariuszy pracy z List<T> w C# jest dodawanie elementów. W przeciwieństwie do tablic (array
), które mają stały rozmiar, lista jest dynamiczną kolekcją – możemy do niej w prosty sposób dodawać i usuwać elementy.
Tworzenie listy i dodawanie elementów metodą Add()
Najprostszy sposób to stworzenie pustej listy i korzystanie z metody .Add()
:
List<string> months = new List<string>();
months.Add("January");
months.Add("February");
months.Add("March");
months.Add("April");
months.Add("May");
months.Add("June");
months.Add("July");
months.Add("August");
months.Add("September");
months.Add("October");
months.Add("November");
months.Add("December");
➡️ Każde wywołanie .Add()
dokłada kolejny element na końcu listy.
Inicjalizator kolekcji – krótsza i czytelniejsza składnia
Podczas korzystania z listy dodawanie to najczęstszy scenariusz. Jeżeli od razu wiemy, jakie dane mają znaleźć się w liście, możemy skorzystać z tzw. inicjalizatora kolekcji, który łączy tworzenie obiektu i dodawanie elementów.
Inicjalizator kolekcji sprawia, że Twój kod jest bardziej zwięzły. Pozwala on też połączyć tworzenie listy z dodaniem początkowego zestawu elementów.
List<string> months = new List<string>
{
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December",
};
To rozwiązanie jest krótsze i bardziej czytelne – zamiast kilkunastu wywołań .Add()
mamy deklarację w jednym miejscu. Jest to prawie identyczne z inicjalizatorem tablicy, który widzieliście na początku przy omawianiu tablic, z elementami które mają znaleźć się na liście w nawiasach klamrowych.
Tablice a listy – różnice przy inicjalizatorach
Tablice (array
) także obsługują inicjalizatory, ale ich składnia jest nieco inna:
string[] monts =
{
"January", "Febrry", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December",
};
Najważniejsze różnice:
- w tablicach słowo kluczowe
new
bywa opcjonalne, w listach jest zawsze wymagane, - tablica ma stały rozmiar, lista może się dynamicznie rozszerzać.
- zarówno tablica, jak i lista używają indeksów, ale w liście masz też metody wysokopoziomowe (
Add
,Remove
,Insert
,Contains
, itp.), które czynią pracę bardziej wygodną. - tablica są szybsze, bo to ciągły blok pamięci. Lista pod spodem i tak korzysta z tablicy, ale musi dbać o dynamiczne rozszerzanie (czasami kosztowne operacje kopiowania).
- tablicę możesz zainicjalizować literałem (
int[] nums = {1,2,3};
). Listę musisz utworzyć przeznew
i ewentualnie przekazać kolekcję startową (new List<int> {1,2,3}
). - tablica świetnie się nadaje, gdy znasz rozmiar z góry i zależy Ci na maksymalnej szybkości. Lista wygrywa, gdy potrzebujesz częstych dodawań/usuwania elementów albo nie znasz rozmiaru na starcie.
tablica = surowa wydajność, lista = wygoda i elastyczność.
Co dzieje się „pod spodem”?
Inicjalizator kolekcji to tylko skrót składniowy. Kompilator w rzeczywistości zamienia powyższy kod na:
var months = new List<string>();
months.Add("January");
months.Add("February");
// ...
months.Add("December");
Czyli pod spodem nadal wykonywane są wywołania .Add()
– różnica polega tylko na czytelniejszej składni.
Kiedy wybrać tablicę, a kiedy listę?
- Tablica (
T[]
) → najlepsza, gdy zbiór ma stałą i znaną z góry liczbę elementów (np. 12 miesięcy, dni tygodnia). - Lista (
List<T>
) → lepsza, gdy liczba elementów jest zmienna, nieznana wcześniej albo dane przychodzą z pliku, bazy czy API.
Podsumowanie
List<T>
umożliwia proste dodawanie elementów dzięki metodzie.Add()
.- Inicjalizator kolekcji (
new List<string> { ... }
) to krótszy zapis, gdy znamy początkowe elementy. - Tablice (
array
) też wspierają inicjalizatory, ale są statyczne – lista daje większą elastyczność. - Pod maską inicjalizator kolekcji i tak wywołuje
.Add()
.
👉 Chcesz poznać więcej o kolekcjach w C# (tablice, listy, kolejki, stosy, słowniki)? Sprawdź kurs:
Wprowadzenie do kolekcji w C# : https://dev-hobby.pl/kursy/c-wprowadzenie-do-kolekcji/
Right away I am going away too do myy breakfast, afterward having my breakfast coming yet again to read further news. Sofia Orbadiah Jaela
I like this blog very much so much great information. Athene Ricky Shaff
I really liked your blog post. Much thanks again. Really Cool. Faunie Gonzalo Davita
Some really nice and useful information on this site, as well I believe the design and style contains great features. Viviana Sterne Gannes
Really appreciate you sharing this article. Really thank you! Cool. Blithe Demetre Morris
Thanks for fantastic info I was looking for this info for my mission. Vivianne Tore Bensky
Great delivery. Great arguments. Keep up the great effort. Linette Shae Chappell
Good day! I simply would like to give an enormous thumbs up for the great information you will have right here on this post. I will probably be coming back to your blog for extra soon. Peggi Drud Giorgia
Its fantastic as your other articles :D, thanks for putting up. Aubree Irving Croft
This is my first time pay a visit at here and i am truly pleassant to read all at one place. Neille Man Esmaria
Really appreciate you sharing this blog post. Will read on Adrea Niel Lovmilla
I blog quite often and I really thank you for your information. Your article has truly peaked my interest. I will take a note of your website and keep checking for new information about once a week. I opted in for your Feed as well. Halley Rodrique Hynda
Hi there friends, its great post concerning teachingand completely explained, keep it up all the time. Kai Gibb Muir
I like a very useful article, I like our page and follow it Ysabel Sollie Sosthena
Well I definitely liked reading it. This subject procured by you is very constructive for accurate planning. Nessy Stearne Lidda
Thanks for your own work on this website. My mum takes pleasure in setting aside time for research and it is simple to grasp why. We notice all relating to the powerful way you provide very important tips and hints via your website and therefore strongly encourage response from visitors on this subject matter while our own simple princess is without a doubt understanding so much. Take pleasure in the rest of the year. Your performing a useful job. Sophey Weber Harrus
Every weekend i used to pay a visit this web site, for the reason that i want enjoyment, since this this site conations actually nice funny information too. Bidget Beltran Emarie
I like reading through a post that can make people think. Also, thank you for permitting me to comment! Mellisa Jan Hilaria
I like the helpful information you supply on your articles. Gretel Leonid Rosenbaum
Amazing! Its actually amazing piece of writing, I have got much clear idea on the topic of from this post. Esther Fin Blancha
Hello to all, how is all, I think every one is getting more from this web site, and your views are pleasant in support of new people. Lind Valle Polivy Cordelie Ingrim Kucik
But wanna remark on few general things, The website design and style is perfect, the subject matter is very superb : D. Xena Granthem Aurora
thanks for providing such helpful data. Jordana Pietrek Stahl Karlen Arlen Elberta
Attractive component of content material. I merely stumbled upon your internet internet site and in accession capital to assert that I acquire in fact appreciated account your blog website posts. Any way I will end up being subscribing in your feeds or even I achievement you get right of entry to continuously quickly. Netti Sid Steve
Pretty! This was an incredibly wonderful article. Thank you for supplying this info. Clarice Isidoro Nobell
wow, awesome article post. Really looking forward to read more. Cool. Gaye Bord Cormier
Looking forward to reading more. Great post. Cool. Ilka James Ger
Hi there, You have performed a great job. I will certainly digg it and for my part suggest to my friends. I am sure they will be benefited from this web site.| Valentia Gilburt Hadwyn
Wonderful article! We will be linking to this particularly great content on our site. Keep up the great writing. Carlotta Truman Ramin
I really like it whenever people come together and share thoughts. Great site, keep it up! Jannelle Templeton Iow
Youre so cool! I dont suppose Ive learn anything like this before. So nice to seek out someone with some authentic ideas on this subject. realy thank you for beginning this up. this web site is something that is needed on the web, someone with a little originality. useful job for bringing one thing new to the internet! Ursula Sylas Franciska
Appreciate it for helping out, fantastic information. Natassia Mendel Ari
Hello mates, nice piece of writing and good urging commented here, I am in fact enjoying by these. Lucina Nat Zalucki
Majątek niektórych przekracza wartość do której potrafią liczyć. Myślą o zemście zamiast umysł Ćwiczyć…