Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

LINQ is for querying! Not for manipulation.

2.50/5 (2 votes)
5 Dec 2011CPOL 23.4K  
Notes regarding LINQ abstraction.

LINQ is all about querying data, not manipulating data.


Manipulate data means to change the data, for example:


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

An example of querying data:


C#
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.)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)