In my code I frequently have the sequences like:
List<type1> list1 = ...;
List<type2> list2 = new List<type2>();
foreach(type1 l1 in list1)
{
list2.Add(myTransformFunc(l1));
}
In Python, I can write it as
list2 = [myTransformFunc(l1) for l1 in list1]
Is there a compact way to write it in C#?
List comprehensions are used for creating new lists from other iterables. As list comprehensions return lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.
List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.
List comprehension is an easy to read, compact, and elegant way of creating a list from any existing iterable object. Basically, it's a simpler way to create a new list from the values in a list you already have. It is generally a single line of code enclosed in square brackets.
var newList = list.Select(x => YourTransformFunc(x)).ToList();
Or:
var newList = list.Select(YourTransformFunc).ToList();
Func signature should be:
type2 YourTransformFunc(type1 value)
{
}
Edit:
Extension methods Select
and ToList
are in System.Linq
namespace.
You are thinking about this:
list1.ForEach(x=> list2.Add(myTransformFunc(x)));
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