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]
1

3 Answers 3

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();
0
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.

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));
1
  • Sorry, I edited my post. But your answer is right, for my original question.
    – hlin117
    Commented Jun 5, 2014 at 14:31

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.