Your Position: Home - Packaging & Printing - LINQ In C#
LINQ in C# is used to work with data access from sources such as objects, data sets, SQL Server, and XML. LINQ stands for Language Integrated Query. LINQ is a data querying API with SQL like query syntaxes. LINQ provides functions to query cached data from all kinds of data sources. The data source could be a collection of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface.
The official goal of the LINQ family of technologies is to add "general purpose query facilities to the .NET Framework that apply to all sources of information, not just relational or XML data".
LINQ to Object provides functionality to query in-memory objects and collections. Any class that implements the IEnumerable<T> interface (in the System.Collections.Generic namespace) can be queried with SQO.
LINQ to ADO.NET deals with data from external sources, basically anything ADO.NET can connect to. Any class that implements IEnumerable<T> or IQueryable<T> (in the System.Query namespace) can be queried with SQO.
LINQ to XML is used to query XML data sources.
Here is a detailed tutorial on LINQ with C# for beginners.
LINQ Code Examples
Here is a simple example that creates a array of integers. A LINQ query is used to return a var that stores the collection of returned data. Learn more: The var keyword in C#.
int[] nums = new int[] {0,1,2};
var res = from a in nums where a < 3 orderby a select a;
foreach(int i in res)
Console.WriteLine(i);
Let's look at a working example. Create a Web page or UI with a GridView control that we will use to display some data. The following code example defines a class, patient with some properties such as name, gender, age, and area.
public class patient
{
public patient()
{
}
// Fields
private string _name;
private int _age;
private string _gender;
private string _area;
// Properties
public string PatientName
{
get { return _name; }
set { _name = value; }
}
public string Area
{
get { return _area; }
set { _area = value; }
}
public String Gender
{
get { return _gender; }
set { _gender = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}
}
Now, on the Web Page (ASP.NET Web Forms in this case), we create a List object dynamically. This program adds a single record but you an add a collection of records. Once the collection is ready, LINQ can be used to query the collection.
In this code, a recorded is queired using LINQ and displayed in a GridView control.
Main Program
using System.Collections.Generic;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<patient> pat=new List<patient>();
patient p=new patient();
p.patientname="Deepak dwij";
p.patientstate = "UP";
p.patientage = "25";
p.patientcity = "Noida";
pat.Add(p);
GridView1.DataSource = from a in pat select a;
GridView1.DataBind();
//GridView1.DataSource = from pa in patients
//where pa.Gender == "Male"
//orderby pa.PatientName, pa.Gender, pa.Age
//select pa;
//GridView1.DataBind();
}
}
The following code uses the selection operator type, which brings all those records whose age is more than 20 years.
var mypatient = from pa in patients
where pa.Age > 20
orderby pa.PatientName, pa.Gender, pa.Age
select pa;
foreach(var pp in mypatient)
{
Debug.WriteLine(pp.PatientName + " "+ pp.Age + " " + pp.Gender);
}
The following code snippet uses the grouping operator type that group patient data on the bases area.
var op = from pa in patients
group pa by pa.Area into g
select new {area = g.Key, count = g.Count(), allpatient = g};
foreach(var g in op)
{
Debug.WriteLine(g.count+ "," + g.area);
foreach(var l in g.allpatient)
{
Debug.WriteLine("\t"+l.PatientName);
}
}
int patientCount = (from pa in patients
where pa.Age > 20
orderby pa.PatientName, pa.Gender, pa.Age
select pa).Count();
Simple select
int[] numbers = { 5, 4, 1, 3, 9, 8};
var numsPlusOne =from n in numbers select n;
foreach (var i in numsPlusOne)
{
MessageBox.Show(i.ToString() );
}
Multiple select
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var pairs =from a in numbersA from b in numbersB where a < b select new { a, b };
Console.WriteLine("Pairs where a < b:");
foreach (var pair in pairs)
{
Console.WriteLine("{0} is less than {1}", pair.a, pair.b);
}
Order by
string[] words = { "cherry", "apple", "blueberry" };
var sortedWords =from w in words orderby w select w;
Console.WriteLine("The sorted list of words:");
foreach (var w in sortedWords)
{
Console.WriteLine(w);
}
Count function
int[] factorsOf300 = { 2, 2, 3, 5, 5 };
int uniqueFactors = factorsOf300.Distinct().Count();
Console.WriteLine("There are {0} unique factors of 300.", uniqueFactors);
OR
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);
Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers);
Continue reading? Here is a detailed tutorial LINQ for Beginners
Fuji Nguyen
·
Follow
Published in
Knowledge Pills
·
2 min read
·
Jan 19
--
LINQ (Language Integrated Query) is a powerful query language built into C# and the .NET Framework. It allows developers to write queries against collections of objects, databases, and XML documents using a syntax that is similar to SQL. LINQ provides a way to filter, sort, and transform data in a more efficient and readable way. Additionally, LINQ supports a variety of query operations such as filtering, ordering, grouping, and joining. It is a powerful tool for working with data in C#.
Here is an example of using LINQ to query data from a database using Entity Framework Core:
using (var context = new ApplicationDbContext())
{
var query = from s in context.Students
where s.Age > 18
select s;
var students = query.ToList();
}
In this example, ApplicationDbContext
is the class that represents the database context, and Students
is a DbSet of Student entities. The query
variable is a LINQ query that selects all students whose age is greater than 18. The ToList()
method is used to execute the query and return the results as a list of Student objects.
Alternatively, it can be written using the method syntax, which is more readable when using more complex queries.
using (var context = new ApplicationDbContext())
{
var students = context.Students
.Where(s => s.Age > 18)
.ToList();
}
LINQ is built into the C# language and the .NET Framework, so there is no need to install a separate NuGet package to use it. You can start using LINQ in your C# projects by including the using System.Linq
namespace at the top of your code file and then using the LINQ query syntax in your code.
234
0
0
Comments
All Comments (0)