65.9K
CodeProject is changing. Read more.
Home

LINQ is for querying! Not for manipulation.

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.50/5 (2 votes)

Nov 9, 2011

CPOL
viewsIcon

23411

Notes regarding LINQ abstraction.

LINQ is all about querying data, not manipulating data.

Manipulate data means to change the data, for example:

List<string> lst = new List<string>();
lst.Add("1"); //this line is changing(manipulate) lst

An example of querying data:

List<string> lst = new List<string>();
var res = lst.where(s => s.StartsWith("1"); //this line is NOT modify lst

Query data is mostly used by using restriction and Projection operators

So now, after we have clarified the distinction between manipulating and querying, let us understand the motivation behind each..

Well, the answer is that LINQ extends IEnumerable*, and IEnumerable is readonly! Therefore manipulating data with IEnumerable will break the abstraction of it.

Then you might ask, why does LINQ extend IEnumerable and not other interfaces which allow to manipulate data?

This is beacause it allows LINQ query operators to be cohesive and focus on the main goal which is to query data. LINQ operators don't care if the collection is readonly or not, adding new functionality to manipulate data will break this abstraction.

The discussion of why LINQ extends IEnumerable/ the benefits and disadvantages of it, is a much wider topic, which I am going to leave open for now..

I leave it to you to wonder why extending IEnumeurable supports the abstraction of LINQ Deferred Execution.

(*Reminder: The IEnumerator interface exposes the Current property, and the Reset and MoveNext methods.)