The LINQ Principle |
Written by Mike James | |||||||||
Thursday, 25 June 2020 | |||||||||
Page 5 of 5
More SelectionUnderstanding how the query expression is converted into calls to the query extension methods greatly clarifies how LINQ works and what you can do with it. If you want to stay with a clear design you should always use Select as a “projection operator”, that is it should reduce the data item to something that is a subset of itself. For example, if the data item is a struct then the select should specify which fields are to be extracted and returned in a “smaller” struct. This is a common and interesting task so let’s look at another simple example of select. First we need a class or struct to hold the data: public struct Contact The default property implementations are just enough code to allow us to initialise a List of such structs directly: List<Contact> AddressBook= As List supports IEnumerator we can now move immediately to using LINQ to query it. To extract a single field, the name say, you would use a query something like: var q = from N in AddressBook Notice the use of var to avoid having to state the data type. If you don’t want to use an anonymous type then you can replace the var with string. It is easy to see how this translates to the call to the select extension method which has to return just the single field as a string but how do you return multiple fields? The problem is that you don’t have a data type, i.e. a struct, that holds a subset of fields. You could define a suitable struct but the standard solution is to create a new anonymous type on the fly: var q = from N in AddressBook You can see that these "dynamic" facilities are required to make LINQ look simple. Other LINQsBasically we have been looking at LINQ to objects but the same principles apply to all the other implementations - LINQ to SQL, XML and ADO for example. You should now be in a position to see how these work even if you still need to dig out the details. What is even more impressive is that if you have a data source that LINQ doesn’t support you should be able to add it by implementing IEnumerable. LINQ is just a powerful and compact way of working with data that many suggest that it should be used in place of alternative methods of processing. In other words use a LINQ expression in favour of a For each loop when ever possible.
To access the code for this project visit the CodeBin.
If you would like to suggest a topic for our Core C# section or if you have any comments contact our C# editor Mike James. Deep C#Buy Now From Amazon Chapter List
Extra Material <ASIN:1871962714> <ASIN:B09FTLPTP9>
Comments
or email your comment to: comments@i-programmer.info
|
|||||||||
Last Updated ( Thursday, 25 June 2020 ) |