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.
append() performs an action on an already existing list. It modifies the list in place instead of of returning a new list.
The usual append method adds the new element in the original sequence and does not return any value.
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 “.
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With