Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an item to a list and return a new list

Tags:

I was asked this question today:

How can I add an item to a list and return that list back?

The code for List<T>.Add(T) returns void. So you can't do something like this:

var list = new List<string>{"item1","item2"}; var newList = list.Add("item3"); 

This is related to using AutoMapper, although that part isn't particularly important.

like image 665
JasonWilczak Avatar asked Nov 24 '15 15:11

JasonWilczak


People also ask

Does append return a new list?

append() performs an action on an already existing list. It modifies the list in place instead of of returning a new list.

Does append return a new list Python?

The usual append method adds the new element in the original sequence and does not return any value.

How do you return a new list in Python?

A Python function can return any object such as a list. To return a list, first create the list object within the function body, assign it to a variable your_list , and return it to the caller of the function using the keyword operation “ return your_list “.


1 Answers

One option is Linq, with Concat:

var list = new List<string>{"item1", "item2"}; var newList = list.Concat(new[] { "item3" }).ToList(); 

In typical Linq fashion, list stays the same, and newList contains all the items from list as well as the items in the new list, in this case just "item3".

You can skip the .ToList() to keep the IEnumerable<string> result if that fits your use case.


If you find yourself doing this often with individual items, you can use something like this extension method to pass them without the new[] { ... } syntax:

public static IEnumerable<T> ConcatItems<T>(this IEnumerable<T> source, params T[] items) {     return source.Concat(items); } 

Because of the params array the earlier example becomes:

var list = new List<string>{"item1", "item2"}; var newList = list.ConcatItems("item3").ToList(); 

Make sure not to mix this up with Union, which removes duplicate items. (Searching for those duplicates is overhead that you probably don't want!)

like image 88
31eee384 Avatar answered Oct 08 '22 20:10

31eee384