Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do lists comprehension (compact way to transform a list into another list) in c#?

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#?

like image 368
Yulia V Avatar asked May 23 '13 11:05

Yulia V


People also ask

Does list comprehension create a new list?

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.

Is list comprehension faster than loop?

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.

What is list comprehension explain with code?

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.


2 Answers

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.

like image 179
tukaef Avatar answered Oct 12 '22 09:10

tukaef


You are thinking about this:

list1.ForEach(x=> list2.Add(myTransformFunc(x)));
like image 24
Piotr Stapp Avatar answered Oct 12 '22 09:10

Piotr Stapp