25

What is the Linq equivalent to the map! or collect! method in Ruby?

   a = [ "a", "b", "c", "d" ]
   a.collect! {|x| x + "!" }
   a             #=>  [ "a!", "b!", "c!", "d!" ]

I could do this by iterating over the collection with a foreach, but I was wondering if there was a more elegant Linq solution.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Jason Marcell
  • 2,785
  • 5
  • 28
  • 41
  • Linq takes a functional approach so you usually won't be doing an in-place modification like in your example above. However, this more matches the expected use of map and collect in ruby (without the !) –  Sep 27 '11 at 16:23

2 Answers2

36

Map = Select

var x = new string[] { "a", "b", "c", "d"}.Select(s => s+"!");
Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132
23

The higher-order function map is best represented in Enumerable.Select which is an extension method in System.Linq.

In case you are curious the other higher-order functions break out like this:

reduce -> Enumerable.Aggregate
filter -> Enumerable.Where

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635