tags:

views:

592

answers:

3

I want to generate a list in C#. I am missing python's list comprehensions. Is there a c# way to create collections on the fly like list comprehensions or generator statements do in python?

+9  A: 

If you are using C# 3.0 (VS2008) then LINQ to Objects can do very similar things:

List<Foo> fooList = new List<Foo>();
IEnumerable<Foo> extract = from foo in fooList where foo.Bar > 10 select Foo.Name.ToUpper();
Matt Campbell
+9  A: 

Matt has mentioned query expressions. These are available for LINQ in general, by the way - not just LINQ to Objects. (For example, the same query applied to a LINQ to SQL datacontext would execute the filter and projection on the database.)

The query expressions in C# 3 are simply syntactic sugar over writing normal C# code - although usually query expressions end up calling extension methods. (They don't have to, and the compiler doesn't care, but they usually do.) There are various things you can do with collections which aren't available in C# query expressions, but which are supported by method calls, so it's worth being aware of both kinds of syntax. For instance, Matt's query expression of:

List<Foo> fooList = new List<Foo>();
IEnumerable<string> extract = from foo in fooList where foo.Bar > 10 select foo.Name.ToUpper();

is "pre-processed" into:

List<Foo> fooList = new List<Foo>();
IEnumerable<string> extract = fooList.Where(foo => foo.Bar > 10)
                                    .Select(foo => foo.Name.ToUpper());

If you want to (say) filter based on the index of the value in the original collection, you can use an appropriate overload of Where which is unavailable via query expressions:

List<Foo> fooList = new List<Foo>();
IEnumerable<string> extract = fooList.Where((foo, index) => foo.Bar > 10 + index)
                                    .Select(foo => foo.Name.ToUpper());

Or you could find the length of the longest name matching the criteria:

List<Foo> fooList = new List<Foo>();
int longestName = fooList.Where((foo, index) => foo.Bar > 10 + index)
                         .Select(foo => foo.Name);
                         .Max();

(You don't have to do the projection and max in separate methods - there's a Max overload which takes a projection as well.)

My point is that using extension methods you can very easily build up sophisticated queries.

You mention Python generators as well - C# has this in the form of iterator blocks. Indeed, these are incredibly useful when implementing LINQ-like operators. (Because most of LINQ to Objects is based on extension methods, you can add your own operators which look "native" to LINQ - although you can't change the query expression syntax yourself.)

Jon Skeet
A: 

List<T>.ConvertAll behaves just like list comprehensions by performing the same operation on every item on an existing list and then returning a new collection. This is an alternative to using Linq especially if you are still using .NET 2.0.

In Python, a simple list comprehension example:

>>> foo = [1, 2, 3]
>>> bar = [x * 2 for x in foo]
>>> bar
[2, 4, 6]

For C# 3.0, you can pass a lambda function specifying what type of mapping function is needed.

public static void Main()
{
    var foo = new List<int>{ 1, 2, 3};
    var bar = foo.ConvertAll(x => x * 2);    // list comprehension

    foreach (var x in bar)
    {
        Console.WriteLine(x);  // should print 2 4 6
    }
}

For C# 2.0, you can use an anonymous method with the Converter delegate to perform the equivalent.

public static void Main()
{
    List<int> foo = new List<int>(new int[]{ 1, 2, 3});
    List<int> bar = foo.ConvertAll(new Converter<int, int>(delegate(int x){ return x * 2; }));  // list comprehension

    foreach (int x in bar)
    {
        Console.WriteLine(x);  // should print 2 4 6
    }
}

(Note: the same can be done with Arrays using Array.ConvertAll

Ray Vega
In Linq, the equivalent would be `var bar = from x in foo select x * 2` as compared to my example `var bar = foo.ConvertAll(x => x * 2)`.Both are comparable in verboseness but the Python example has them both beat in the least amount of code overall. :-)
Ray Vega