LINQ stands for Language Integrated Query.
LINQ enables us to query any type of data i.e.SQL Server, XML documents, Objects in memory etc.
If the .NET application that is being developed
a) Requires data from SQL Server - Then the developer has to understand ADO.NET code and SQL specific to SQL Server Database
b) Requires data from an XML document - Then the developer has to understand XSLT & XPATH queries
c) Need to query objects in memory (List<Customer>, List<Order> etc) - Then the developer has to understand how to work with objects in memory
LINQ enables us
to work with these different data sources using a similar coding style
without having the need to know the syntax specific to the data source.
In our upcoming videos we will discuss querying different data sources
using LINQ.
Another benefit of using LINQ is that it provides intellisense and compile time error checking.
1. LINQ query can be written using any .NET supported programming language
2. LINQ
provider is a component between the LINQ query and the actual data
source, which converts the LINQ query into a format that the underlying
data source can understand. For example LINQ to SQL provider converts a
LINQ query to T-SQL that SQL Server database can understand.
Please see the below LINQ archicture
Showing posts with label linq. Show all posts
Showing posts with label linq. Show all posts
Oct 29, 2014
Apr 17, 2014
Entity Framework vs LINQ-to-SQL:
You may think that what is the difference between Entity Framework
and LINQ to SQL which does that same thing. There are some differences
between Entity Framework and L2S.
- Entity framework has a full provider model. It supports not only SQL Server but also other database like Oracle, DB2, MySQL etc.
- Most of the time L2S classes must be one-to-one with database objects e.g. Customer class can be mapped only with Customer table. Where as in Entity Framework you can map your domain class with multiple tables using various inheritance strategies like table per type (class) or table per hierarchy of classes etc.
- You can have multiple modeling techniques using Entity Framework 4.1 like code first, model first or database first.
Labels:
Entity Framework,
linq
Aug 13, 2012
Advantages of LINQ over Stored Procedures
1. It stands for Language Integrated Query. LINQ is collection of standard query operators that provides the query facilities into .NET framework language like C#.
2. Debugging: It is really very hard to debug the stored procedure but as LINQ is part of .NET, you can use visual studio's debugger to debug the queries.
3. Deployment: With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.
4. Type Safety: LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception!
5. Abstraction: This is especially true with LINQ-to-Entities. This abstraction also allows the framework to add additional improvements that you can easily take advantage of. PLINQ is an example of adding multi-threading support to LINQ. Code changes are minimal to add this support. It would be MUCH harder to do this data access code that simply calls stored procedures.
6. Debugging support: I can use any .NET debugger to debug the queries. With stored procedures, you cannot easily debug the SQL and that experience is largely tied to your database vendor (MS SQL Server provides a query analyzer, but often that isn't enough).
7. Vendor agnostic: LINQ works with lots of databases and the number of supported databases will only increase. Stored procedures are not always portable between databases, either because of varying syntax or feature support (if the database supports stored procedures at all).
8. Easier: You don't have to learn T-SQL to do data access, nor do you have to learn the data access API (e.g. ADO.NET) necessary for calling the stored procedures.
9. Not just tables in a relational database: LINQ's benefits include, most significantly, a standardized way to query not just tables in a relational database but also text files, XML files, and other data sources using identical syntax. A second benefit is the ability to use this standardized method from any .NET-compliant language such as C#, VB.NET, and others.
10. Collections like arrays: It allows you to query collections like arrays, enumerable classes etc in the native language of your application, and like VB or C# in much the same way as you would query a database using SQL. LINQ to SQL, which is what most of the current fuss is about, is an Object/Relational Mapper (O/RM) built in to Visual Studio.
11. Entity classes: It automatically generates entity classes based on the database schema, so it helps speed up development of n-layer architecture applications.
12. Faster to Develop: LINQ to SQL is not necessarily going to speed up data access code. Since LINQ to SQL is abstraction over the low level ADO.NET command and connection classes, it's bound to be a bit slower at runtime (but hopefully faster to develop with).
13. Amount of Code: It seems to me that the main advantage of Linq over writing a stored procedure in management studio is the hard typing of tables and parameters and auto completion of column names. The amount of code to connect to the database is significantly reduced - to one or two lines making code much more readable and removing coding errors.
14. Code is much more robust: You get auto complete on the (column / field names) and an error if you mistype or mismatch - your code is much more robust.
15. Filtering and Grouping : Say you access your code via a stored procedure (to apply filtering, grouping, join etc) and you (or someone edits) your stored procedure, to add a (returned) column which happens to be the 3rd column of 7: then that will break your code which refers to ordinal position. Actually if you got to the spec for SQL, you will find that ordinal position on a table may not be maintained, where as column name is guaranteed.
16. No ordinal position problem: Now that the ordinal position problem in the VB implementation is fixed you can happily manipulate to your heart’s content.
17. Easier to transform data into objects: Makes it easier to transform data into objects. I'm sure you've heard the term "Impedence Mismatch" being used quite often, meaning that LINQ reduces the amount of work you must do to translate between object-oriented code and data paradigms such as hierarchical, flat-file, messages, relational, and more. It doesn't eliminate the "Impedence Mismatch" because you must still reason about your data in its native form, but the bridge from here to there is (IMO) much shorter.
18. Common syntax: A common syntax for all data. Once you learn query syntax, you can use it with any LINQ provider. I think this is a much better development paradigm than the Tower of Babel that has grown over the years with data access technologies. Of course, each LINQ provider has unique nuances that are necessary, but the basic approach and query syntax is the same.
19. Strongly typed code: The C# (or VB.NET) query syntax is part of the language and you code with C# types, which are translated into something a provider understands. This means that you gain the productivity of having your compiler find errors earlier in the development lifecycle than elsewhere. Granted, many errors in stored proc syntax will generate errors when you save, but LINQ is more general than SQL Server. You have to think of all the other types of data sources that generate runtime errors because their queries are formed with strings or some other loosely typed mechanism.
20. Provider integration: Pulling together data sources is very easy. For example, you can use LINQ to Objects, LINQ to SQL, and LINQ to XML together for some very sophisticated scenarios. I think it's very elegant.
21. Reduction in work: Before LINQ, I spent a lot of time building DALs, but now my DataContext is the DAL. I've used OPFs too, but now I have LINQ that ships with multiple providers in the box and many other 3rd party providers, giving me the benefits from my previous points. I can set up a LINQ to SQL DataContext in a minute (as fast as my computer and IDE can keep up).
22. Performance in the general case doesn't become an issue: SQL Server optimizes queries quite well these days, just like stored procedures. Of course, there are still cases where stored procedures are necessary for performance reasons. For example, I've found it smarter to use a stored proc when I had multiple interactions between tables with additional logic inside of a transaction. The communications overhead of trying to do the same task in code, in addition to getting the DTC involved in a distributed transaction made the choice for a stored proc more compelling. However, for a query that executes in a single statement, LINQ is my preferred choice because even if there was a small performance gain from a stored proc, the benefits in previous points (IMO) carry more weight.
23. Built-in security: One reason I preferred stored procedures before LINQ was that they forced the use of parameters, helping to reduce SQL injection attacks. LINQ to SQL already parameterizes input, which is just as secure.
24. LINQ is declarative: A lot of attention is paid to working with LINQ to XML or LINQ to SQL, but LINQ to Objects is incredibly powerful. A typical example of LINQ to Objects is reading items from a string[]. However, that's just a small example. If you think about all of the IEnumerable collections (you can also query IEnumerable) that you work with every day, the opportunities are plentiful. i.e. Searching an ASP.NET ListBox control for selected items, performing set operations (such as Union) on two collections, or iterating through a List and running a lambda in a ForEach of each item. Once you begin to think in LINQ, which is declarative in nature, you can find many of your tasks to be simpler and more intuitive than the imperative techniques you use today.
2. Debugging: It is really very hard to debug the stored procedure but as LINQ is part of .NET, you can use visual studio's debugger to debug the queries.
3. Deployment: With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.
4. Type Safety: LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception!
5. Abstraction: This is especially true with LINQ-to-Entities. This abstraction also allows the framework to add additional improvements that you can easily take advantage of. PLINQ is an example of adding multi-threading support to LINQ. Code changes are minimal to add this support. It would be MUCH harder to do this data access code that simply calls stored procedures.
6. Debugging support: I can use any .NET debugger to debug the queries. With stored procedures, you cannot easily debug the SQL and that experience is largely tied to your database vendor (MS SQL Server provides a query analyzer, but often that isn't enough).
7. Vendor agnostic: LINQ works with lots of databases and the number of supported databases will only increase. Stored procedures are not always portable between databases, either because of varying syntax or feature support (if the database supports stored procedures at all).
8. Easier: You don't have to learn T-SQL to do data access, nor do you have to learn the data access API (e.g. ADO.NET) necessary for calling the stored procedures.
9. Not just tables in a relational database: LINQ's benefits include, most significantly, a standardized way to query not just tables in a relational database but also text files, XML files, and other data sources using identical syntax. A second benefit is the ability to use this standardized method from any .NET-compliant language such as C#, VB.NET, and others.
10. Collections like arrays: It allows you to query collections like arrays, enumerable classes etc in the native language of your application, and like VB or C# in much the same way as you would query a database using SQL. LINQ to SQL, which is what most of the current fuss is about, is an Object/Relational Mapper (O/RM) built in to Visual Studio.
11. Entity classes: It automatically generates entity classes based on the database schema, so it helps speed up development of n-layer architecture applications.
12. Faster to Develop: LINQ to SQL is not necessarily going to speed up data access code. Since LINQ to SQL is abstraction over the low level ADO.NET command and connection classes, it's bound to be a bit slower at runtime (but hopefully faster to develop with).
13. Amount of Code: It seems to me that the main advantage of Linq over writing a stored procedure in management studio is the hard typing of tables and parameters and auto completion of column names. The amount of code to connect to the database is significantly reduced - to one or two lines making code much more readable and removing coding errors.
14. Code is much more robust: You get auto complete on the (column / field names) and an error if you mistype or mismatch - your code is much more robust.
15. Filtering and Grouping : Say you access your code via a stored procedure (to apply filtering, grouping, join etc) and you (or someone edits) your stored procedure, to add a (returned) column which happens to be the 3rd column of 7: then that will break your code which refers to ordinal position. Actually if you got to the spec for SQL, you will find that ordinal position on a table may not be maintained, where as column name is guaranteed.
16. No ordinal position problem: Now that the ordinal position problem in the VB implementation is fixed you can happily manipulate to your heart’s content.
17. Easier to transform data into objects: Makes it easier to transform data into objects. I'm sure you've heard the term "Impedence Mismatch" being used quite often, meaning that LINQ reduces the amount of work you must do to translate between object-oriented code and data paradigms such as hierarchical, flat-file, messages, relational, and more. It doesn't eliminate the "Impedence Mismatch" because you must still reason about your data in its native form, but the bridge from here to there is (IMO) much shorter.
18. Common syntax: A common syntax for all data. Once you learn query syntax, you can use it with any LINQ provider. I think this is a much better development paradigm than the Tower of Babel that has grown over the years with data access technologies. Of course, each LINQ provider has unique nuances that are necessary, but the basic approach and query syntax is the same.
19. Strongly typed code: The C# (or VB.NET) query syntax is part of the language and you code with C# types, which are translated into something a provider understands. This means that you gain the productivity of having your compiler find errors earlier in the development lifecycle than elsewhere. Granted, many errors in stored proc syntax will generate errors when you save, but LINQ is more general than SQL Server. You have to think of all the other types of data sources that generate runtime errors because their queries are formed with strings or some other loosely typed mechanism.
20. Provider integration: Pulling together data sources is very easy. For example, you can use LINQ to Objects, LINQ to SQL, and LINQ to XML together for some very sophisticated scenarios. I think it's very elegant.
21. Reduction in work: Before LINQ, I spent a lot of time building DALs, but now my DataContext is the DAL. I've used OPFs too, but now I have LINQ that ships with multiple providers in the box and many other 3rd party providers, giving me the benefits from my previous points. I can set up a LINQ to SQL DataContext in a minute (as fast as my computer and IDE can keep up).
22. Performance in the general case doesn't become an issue: SQL Server optimizes queries quite well these days, just like stored procedures. Of course, there are still cases where stored procedures are necessary for performance reasons. For example, I've found it smarter to use a stored proc when I had multiple interactions between tables with additional logic inside of a transaction. The communications overhead of trying to do the same task in code, in addition to getting the DTC involved in a distributed transaction made the choice for a stored proc more compelling. However, for a query that executes in a single statement, LINQ is my preferred choice because even if there was a small performance gain from a stored proc, the benefits in previous points (IMO) carry more weight.
23. Built-in security: One reason I preferred stored procedures before LINQ was that they forced the use of parameters, helping to reduce SQL injection attacks. LINQ to SQL already parameterizes input, which is just as secure.
24. LINQ is declarative: A lot of attention is paid to working with LINQ to XML or LINQ to SQL, but LINQ to Objects is incredibly powerful. A typical example of LINQ to Objects is reading items from a string[]. However, that's just a small example. If you think about all of the IEnumerable
Labels:
linq,
stored procedure
Jul 29, 2012
Simple Filtering using Lamda expression in Linq using C#.net
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Linq;
namespace Linq_ex
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Simple Filtering using Lamda expression
private void button2_Click(object sender, EventArgs e)
{
var word1 = from word in "hi this is vamsi testing linq".Split() orderby word.Length descending select word;
IEnumerable<string> test = System.Linq.Enumerable.Where(word1, n => n.Length >= 4);
foreach (string n in test)
{
MessageBox.Show(n + "|");
}
}
Out put will be:
TESTING
VAMSI
LiNQ
LiNQ
THIS
Labels:
Lamda expression,
linq,
Linq with C#.net
Linq sample program with C#.net to change upper case to given string
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
// need to add Linq sample
using System.Linq;
namespace Linq_ex
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var word1 = from word in "hi this is vamsi testing linq".Split() orderby word.Length descending select word.ToUpper();
//.ToUpper() -- for upper case output
//.ToLower() -- for lower case output
foreach (string w1 in word1)
{
MessageBox.Show(w1);
}
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
// need to add Linq sample
using System.Linq;
namespace Linq_ex
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var word1 = from word in "hi this is vamsi testing linq".Split() orderby word.Length descending select word.ToUpper();
//.ToUpper() -- for upper case output
//.ToLower() -- for lower case output
foreach (string w1 in word1)
{
MessageBox.Show(w1);
}
}
}
}
The Output will be like
TESTING
VAMSI
KINQ
KINQ
THIS
IS
IS
HI
Labels:
linq,
Linq with C#.net
Linq sample program with C#.net
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
// need to add Linq sample
using System.Linq;
namespace Linq_ex
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var word1 = from word in "hi this is vamsi testing linq".Split() orderby word.Length descending select word;
foreach (string w1 in word1)
{
MessageBox.Show(w1);
}
}
}
}
The Output will be like
testing
vamsi
linq
linq
this
is
hi
is
hi
Labels:
linq,
Linq with C#.net
Jun 22, 2011
Get A List Of Installed Applications Using LINQ And C#
To get a list of installed applications we need to look into registry. Microsoft.Win32 namespace contains objects which can be used to work with Windows Registry. In this post I will show you some code where I use the power of LINQ to retrieve and display a list of all applications installed on a machine.
The basic idea is that we iterate through a collection of RegistryKey objects within LocalMachine\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall. We then open the sub keys and get the DisplayName.
Here is the code:
static void DisplayInstalledApplications()
{
string registryKey =
@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (Microsoft.Win32.RegistryKey key =
Registry.LocalMachine.OpenSubKey(registryKey))
{
var query = from a in
key.GetSubKeyNames()
let r = key.OpenSubKey(a)
select new
{
Application = r.GetValue("DisplayName")
};
foreach (var item in query)
{
if (item.Application != null)
Console.WriteLine(item.Application);
}
}
}
I can also make this a bit more LINQed by removing the foreach loop. It just adds a bit more C# 3.0 flavour to the code and does the retrieval and writing to console in one line.
static void DisplayInstalledApplications2()
{
string registryKey =
@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (Microsoft.Win32.RegistryKey key =
Registry.LocalMachine.OpenSubKey(registryKey))
{
(from a in key.GetSubKeyNames()
let r = key.OpenSubKey(a)
select new
{
Application = r.GetValue("DisplayName")
}).ToList()
.FindAll(c => c.Application != null)
.ForEach(c => Console.WriteLine(c.Application));
}
}
Labels:
c#.net,
linq,
Sysprogrtamming
Jan 8, 2010
CSV to XML Conversion using LINQ
on C#, if we want to Convert CSV to XML then you can use Language
Integrated Query (LINQ) can be used to convert a CSV file to XML. Here
is the sample CSV file that needs to be converted
below example code reads the CSV file to an array. LINQ is used to loop through the array and the contents are written as XML using XElement (System.XML.Linq).
using this you can convert your CSV file xml using C# and C# Convert CSV To XML, .NET CSV To XML
below example code reads the CSV file to an array. LINQ is used to loop through the array and the contents are written as XML using XElement (System.XML.Linq).
public void ConvCSVToXML()
{
String[] FileContent = File.ReadAllLines(@"D:\Proj\jquery.csv");
String XMLNS = "";
XElement Inv = new XElement("type", from
items in FileContent
let fields = items.Split(',')
select new XElement("fadein",
new XElement("Tab", fields[0]),
new XElement("ProgressBar", fields[1]),
new XElement("ToolTip", fields[2]),
new XElement("Menu", fields[3]),
)
);
File.WriteAllText(@"D:\Proj\jquery.xml", XMLNS + Inv.ToString() );
}
using this you can convert your CSV file xml using C# and C# Convert CSV To XML, .NET CSV To XML
Subscribe to:
Posts (Atom)