Why is the LINQ “apply-to-all” method named Select

2019-03-22 15:42发布

问题:

When I read code that uses Select I think "select-all-where". When I read code that uses Map I think "this-to-that" or "apply-to-all". I can't be the only person that feels the name Select is confusing.

Map

回答1:

It's really identical to map from functional languages. The reason it's named Select is that it's designed to be used as a part of LINQ which uses SQL-like keywords.

from item in collection
where item.Value == someValue
select item.Name

is translated to:

collection.Where(item => item.Value == someValue)
          .Select(item => item.Name)

it would be a little inconsistent if Select was named Map; something like:

collection.Filter(item => item.Value == someValue)
          .Map(item => item.Name)

In fact, many people use LINQ without having heard of functional programming at all. To them, LINQ is a method to retrieve data objects and query them easily (like SQL queries are). To them, Select and Where make perfect sense. Much more than Map and Filter.



回答2:

At first Select seemed little confusing for me too, but it was only a matter of time. Mehrdad tells you a good reason for Select. Other than that I feel Select conveys the immutability aspect of Linq much better. Not that Map would mean it's mutating the original structure, but Select states it much clearer. It tells you're not touching the original list but merely selecting from it to form another list.

It goes with other naming as well like Where. When you call collection.Filter it gives you an idea that you're filtering on that particular collection, or at least the first time. In the end it's all a matter of getting familiarized. Though in the beginning I was so annoyed by the Linq namings, now I feel MS team has got it the most correct.



回答3:

One of the major reasons Select comes last is to make Intellisense work. By putting the source of the sequence first (from statement), Intellisense can work properly.