Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Map! or Collect!

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.

like image 513
Jason Marcell Avatar asked Mar 31 '09 17:03

Jason Marcell


People also ask

What is LINQ to lists/collection?

LINQ to Lists/collection means writing the LINQ queries on list or collection. By using LINQ queries on the collection or list, we can filter or sort or remove the duplicates elements with minimal coding. Here is the syntax of writing the LINQ queries on the list or collection to get the required elements.

Where is LINQ extension method used to filter the collection?

LINQ Where is a LINQ extension method which is used to filter the collection of elements based on the given condition? The condition can be precise as Func delegate type or in the lambda expression. This will be applicable in method syntax as well as in query syntax. In a single query, we can do multiple where extension methods.

How where works in LINQ?

How Where Works in LINQ? The main purpose of LINQ where is used to filter elements based on the conditions. It comes under the filtering operator category. It applies in both method and query syntax whereas method syntax requires the lambda expression and query syntax requires only the expression.

How to remove duplicates from a list or collection using LINQ?

By using LINQ queries on the collection or list, we can filter or sort or remove the duplicates elements with minimal coding. Here is the syntax of writing the LINQ queries on the list or collection to get the required elements.


2 Answers

Map = Select

var x = new string[] { "a", "b", "c", "d"}.Select(s => s+"!"); 
like image 171
Quintin Robinson Avatar answered Oct 09 '22 00:10

Quintin Robinson


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

like image 33
Andrew Hare Avatar answered Oct 09 '22 00:10

Andrew Hare