1

Python offers the following syntax to initialize a python List functionally:

mylist = [item for item in iterable]

Is there a similar syntax in C# for initializing a C# List?

EDIT:

I guess I should be more specific. I'm trying to emulate the following syntax:

mylist = [operation(item) for item in iterable]
hlin117
  • 20,764
  • 31
  • 72
  • 93
  • [List Constructor (IEnumerable)](http://msdn.microsoft.com/en-us/library/fkbw11z0.aspx)? – GSerg Jun 05 '14 at 14:24

3 Answers3

4

Assuming iterable is an IEnumerable<T> of some sort, you can use the List<T>(IEnumerable<T>) constructor overload to initialize a new list:

mylist = new List(iterable); 

You can also call the Linq Enumberable.ToList extension method:

mylist = iterable.ToList();

Specifically, it looks like you're after how to do the equivalent of list comprehension. You can use Linq's Enumerable.Select method and a lambda. For example, to match your edit:

mylist = iterable.Select(item => operation(item)).ToList();

As a bonus, if you were trying to do the following (adding a condition):

mylist = [operation(item) for item in iterable if item > 42]

You would add a call to Enumerable.Where in the chain:

mylist = iterable.Where(item => item > 42).Select(item => operation(item)).ToList();
lc.
  • 113,939
  • 20
  • 158
  • 187
0

You may create a C# List of items, say ints, in the following manor:

List<int> myList = new List<int>{1, 2, 3, 4,};

So you don't need to specify the initial size, it infers it from your initial objects. If you instead have an enumerable, see the code below

IEnumerable<int> existingEnumerable = ...
List<int> myList = new List<int>(existingEnumerable);

Let us know if this fits your needs.

GEEF
  • 1,175
  • 5
  • 17
0

It appears you just turn an iterable collection into an array.

In C#, there is a .ToArray() extension method on a collection type. Maybe that is what you need.

It would be:

result=iterable.ToArray();

after the edit, it appears you are to transform list.

myList=iterable.Select(i=> Operation(i));
Blaise
  • 21,314
  • 28
  • 108
  • 169