Questions tagged [linq]

Language Integrated Query (LINQ) is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages. Please consider using more detailed tags when appropriate, for example [linq-to-sql], [linq-to-entities] / [entity-framework], or [plinq]

This tag is for questions about , a .NET-based DSL (Domain Specific Language), introduced in , for querying data sources such as databases, XML files or in-memory object lists.

Please consider using more detailed tags when appropriate, for example , / , or .

About LINQ

All data sources can be queried using the exact same, readable and easy-to-use syntax - or rather, syntaxes, because LINQ supports two notations:

  • Inline LINQ or query syntax, where queries are expressed in a SQL-like language, with dialects in both C# and VB.NET.

  • Fluent LINQ or query operators, where queries are expressed as lambda expressions and can be linked (LINQed?) using a fluent syntax.

All LINQ query operations consist of three distinct actions:

  1. Obtain the data source.
  2. Create the query.
  3. Execute the query.

Major Implementations:

.NET languages: C#, F#, VB.NET

Some examples:

Fluent syntax (C#)

var result = dbContext.Products
                      .Where(p => p.Category.Name == "Toys" && p.Price >= 2.50)
                      .Select(p => p.Name);

Query syntax (C#)

var result = from product in dbContext.Products
             where product.Category.Name == "Toys"
             where product.Price >= 2.50
             select product.Name;

Query syntax (VB.NET)

Dim result = From product in dbContext.Products _
             Where product.Category.Name = "Toys" _
             Where product.Price >= 2.50 _
             Select product.Name

This query would return the name of all products in the "Toys" category with a price greater than or equal to 2.50.

Flavors

LINQ comes in many flavors, the most notable are

Other implementations of LINQ can be found on the Internet, such as LINQ to SharePoint, LINQ to Twitter, LINQ to CSV, LINQ to Excel, LINQ to JSON and LINQ to Google.

There are also lots of extensions for LINQ available, which add more operators to the ones .NET offers. A variety of those are open-source projects, for example MoreLINQ.

Resources

86142 questions
22
votes
2 answers

Create Dictionary with LINQ and avoid "item with the same key has already been added" error

I want to find a key in a dictionary and replace the value if it is found or add the key/value if it is not. Code: public class MyObject { public string UniqueKey { get; set; } public string Field1 { get; set; } public string Field2 {…
TomSelleck
  • 6,706
  • 22
  • 82
  • 151
22
votes
1 answer

De/Serialize directly To/From XML Linq

Is there any way to de/serialize an object without round-tripping a XmlDocument/temp string? I am looking for something like the following: class Program { static void Main(string[] args) { XDocument doc = new XDocument(); …
Jonathan C Dickinson
  • 7,181
  • 4
  • 35
  • 46
22
votes
4 answers

Which LINQ statements force Entity Framework to return from the DB?

I know of several LINQ statements that will cause EF to evaluate and return results form the DB to memory. .ToList() is one. Does anyone have a comprehensive list of the statements that do this? Not sure of... .SingleOrDefault() .Union() EDIT:…
jrizzo
  • 1,652
  • 4
  • 17
  • 29
22
votes
9 answers

Interview Question: .Any() vs if (.Length > 0) for testing if a collection has elements

In a recent interview I was asked what the difference between .Any() and .Length > 0 was and why I would use either when testing to see if a collection had elements. This threw me a little as it seems a little obvious but feel I may be missing…
Chris
  • 26,744
  • 48
  • 193
  • 345
22
votes
2 answers

Linq and conditional sum

I have a class and a list as below: class C1 { int RecType ...; decimal Income ...; decimal Outcome ...; } List myList ...; The list is loaded with several records, and they have various values in RecType What I want is to…
bzamfir
  • 4,698
  • 10
  • 54
  • 89
22
votes
6 answers

Most efficient way to update with LINQ to SQL

Can I update my employee record as given in the function below or do I have to make a query of the employee collection first and then update the data? public int updateEmployee(App3_EMPLOYEE employee) { DBContextDataContext db = new…
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
22
votes
2 answers

LINQ Lambda vs Query Syntax Performance

I saw a LINQ query syntax in my project today which was counting items with a specific condition from a List like this: int temp = (from A in pTasks where A.StatusID == (int)BusinessRule.TaskStatus.Pending select…
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
22
votes
6 answers

Make CSV from list of string in LINQ

Hi I would like to take a list collection and generate a single csv line. So take this; List MakeStrings() { List results = new List(); results.add("Bob"); results.add("Nancy"); results.add("Joe"); …
CmdrTallen
  • 2,264
  • 4
  • 28
  • 50
22
votes
5 answers

What's FirstOrDefault for DateTime in Linq?

If I have a query that returns a DateTime, what's the value of FirstOrDefault()? Is there a generic way to get the default value of a C# scalar? Example: var list = (from item in db.Items where item.ID==1234 select…
Keltex
  • 26,220
  • 11
  • 79
  • 111
22
votes
4 answers

Create combined DataTable from two DataTables joined with LINQ. C#

I have the following code that fills dataTable1 and dataTable2 with two simple SQL queries, dataTableSqlJoined is filled from the same tables but joined together. I'm trying to write a LINQ query that can create the dataTableLinqJoined as if it had…
Robin Day
  • 100,552
  • 23
  • 116
  • 167
22
votes
5 answers

c# dictionary get the key of the min value

probably a simple one for you today but I'm currently going round in circles. Consider this scenario: var tempDictionary = new Dictionary(); tempDictionary.Add("user 1", 5); tempDictionary.Add("user 2", 3); tempDictionary.Add("user 3",…
Dezzamondo
  • 2,169
  • 2
  • 20
  • 33
22
votes
1 answer

How do I create a Linq expression tree with an F# lambda?

Here's what can be done in C# - var two = 2; System.Linq.Expressions.Expression> expr = x => x * two; expr.Compile().Invoke(4); // returns 8 I wish to do the precise equivalent in F#. Here's what I tried, but did not compile…
Bryan Edds
  • 1,696
  • 12
  • 28
22
votes
2 answers

Match elements between 2 collections with Linq in c#

i have a question about how to do a common programming task in linq. lets say we have do different collections or arrays. What i would like to do is match elements between arrays and if there is a match then do something with that element. eg: …
Grant
  • 11,138
  • 32
  • 94
  • 140
22
votes
3 answers

Linq Count with Condition

I want to provide 2 condition's in the COUNT clause for checking ROLE & USERID. Here is my code :- var recordCount = ctx.Cases.Count(); How to give Where condition in Count()?
Anup
  • 9,396
  • 16
  • 74
  • 138
22
votes
5 answers

PagedList using LINQ Skip and Take, but show paging using Count of results

I am trying to display a filtered list of of products, based on Category filter and ItemsPerPage but I'm having some issues when trying to use it with PagedList. Someone with PagedList expertise could advice me if I need to write my own pagination…
badboy11
  • 541
  • 1
  • 6
  • 19