Tips and tricks for writing LINQ.

In this article, I have demonstrated few tips for LINQ beginners. It contains short code snippets which can be used in your applications where usage of LINQ is necessary. LINQ has very good features which can be used to retrieve data from tables effectively.

1. How to retrieve first n rows from table using LINQ?

var data = (from std in students
select std).Take(100);

It will take first 100 rows and display it.
2. How to skip n rows from table using LINQ?

var data = (from std in students
select std).Skip(100);

3.Use naming conventions meaningful for query variables. For e.g. If you want to retrieve data of students who got first class then query will be as follows:

var firstclassStudentsData = from std in students
where std.Class == "First"
select std.Name;

firstclassStudentsData is meaningful name for query variable.
Align query clauses under the from clause same as mentioned in above query.
If you want to retrieve data from multiple tables then use multiple from clauses instead of a join clause to access inner collections.
When there is ambiguous results for e.g. ID , name etc then you have to rename properties so that clarity will be more.
When you want to sort results using orderby clause then always put where clause first so that data will be filtered as per condition there itself and then use orderby clause for sorting.

var firstclassStudentsData = from std in students
where std.Class == "First"
orderby std.Name
select std;

In orderby you can mention ascending or descending or default.
Use Pascal casing for making aliases so that property names which is of anonymous types are correctly capitalized.
Deferred loading or lazy-loading can be disabled or enabled on the data context by setting DeferredLoadingEnabled property. If it is not required to load child data along with parent data then lazy loading should be false.
10.Use of FirstOrDefault()
when you are sure that data will contain single row or topmost row or default data then always better to use FirstOrDefault().
11.How to make LINQ class serializable?
If you want to make the LINQ class serializable, you'll need to mark all System.Data.Linq.EntitySet and System.Data.Linq.EntityRef fields with NonSerialized attribute and to mark with Serializable attribute the LINQ class.
12. What is Attach method?
Attach method allows you to update entities that have changed outside the context.


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: