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
330
votes
17 answers

Entity Framework: There is already an open DataReader associated with this Command

I am using Entity Framework and occasionally i will get this error. EntityCommandExecutionException {"There is already an open DataReader associated with this Command which must be closed first."} at…
Sonic Soul
  • 23,855
  • 37
  • 130
  • 196
328
votes
8 answers

Async await in linq select

I need to modify an existing program and it contains following code: var inputs = events.Select(async ev => await ProcessEventAsync(ev)) .Select(t => t.Result) .Where(i => i != null) …
Alexander Derck
  • 13,818
  • 5
  • 54
  • 76
324
votes
6 answers

Convert string[] to int[] in one line of code using LINQ

I have an array of integers in string form: var arr = new string[] { "1", "2", "3", "4" }; I need to an array of 'real' integers to push it further: void Foo(int[] arr) { .. } I tried to cast int and it of course…
abatishchev
  • 98,240
  • 88
  • 296
  • 433
319
votes
18 answers

Quickest way to compare two generic lists for differences

What is the quickest (and least resource intensive) to compare two massive (>50.000 items) and as a result have two lists like the ones below: items that show up in the first list but not in the second items that show up in the second list but not…
Frank
  • 3,959
  • 4
  • 19
  • 24
317
votes
10 answers

Combining two expressions (Expression>)

I have two expressions of type Expression> and I want to take to OR, AND or NOT of these and get a new expression of the same type Expression> expr1; Expression> expr2; ... //how to do this (the code below…
BjartN
  • 5,327
  • 6
  • 28
  • 32
310
votes
8 answers

LINQ: Not Any vs All Don't

Often I want to check if a provided value matches one in a list (e.g. when validating): if (!acceptedValues.Any(v => v == someValue)) { // exception logic } Recently, I've noticed ReSharper asking me to simplify these queries to: if…
Mark
  • 3,372
  • 2
  • 16
  • 14
303
votes
3 answers

LINQ with groupby and count

This is pretty simple but I'm at a loss: Given this type of data set: UserInfo(name, metric, day, other_metric) and this sample data set: joe 1 01/01/2011 5 jane 0 01/02/2011 9 john 2 01/03/2011 0 jim 3 01/04/2011 1 jean 1 01/05/2011 3 jill 2…
Gio
  • 4,099
  • 3
  • 30
  • 32
303
votes
5 answers

Why does ReSharper tell me "implicitly captured closure"?

I have the following code: public double CalculateDailyProjectPullForceMax(DateTime date, string start = null, string end = null) { Log("Calculating Daily Pull Force Max..."); var pullForceList = start == null ?…
PiousVenom
  • 6,888
  • 11
  • 47
  • 86
301
votes
13 answers

How to do joins in LINQ on multiple fields in single join

I need to do a LINQ2DataSet query that does a join on more than one field (as var result = from x in entity join y in entity2 on x.field1 = y.field1 and x.field2 = y.field2 I have yet found a suitable solution (I can add the…
johnc
  • 39,385
  • 37
  • 101
  • 139
298
votes
12 answers

Sorting a list using Lambda/Linq to objects

I have the name of the "sort by property" in a string. I will need to use Lambda/Linq to sort the list of objects. Ex: public class Employee { public string FirstName {set; get;} public string LastName {set; get;} public DateTime DOB {set;…
DotnetDude
  • 11,617
  • 35
  • 100
  • 158
292
votes
9 answers

How can I get the index of an item in a list in a single step?

How can I find the index of an item in a list without looping through it? Currently this doesn't look very nice - searching through the list for the same item twice, just to get the index: var oProp = something; int theThingIActuallyAmInterestedIn…
Daniel Robinson
  • 13,806
  • 18
  • 64
  • 112
291
votes
8 answers

How to get values from IGrouping

I have a question about IGrouping and the Select() method. Let's say I've got an IEnumerable> in this way: var groups = list.GroupBy(x => x.ID); where list is a List. And now I need to pass values of each IGrouping to…
Illia Ratkevych
  • 3,507
  • 4
  • 29
  • 35
291
votes
4 answers

How to merge a list of lists with same type of items to a single list of items?

The question is confusing, but it is much more clear as described by the following code: List> listOfList; // add three lists of List to listOfList, for example /* listOfList = new { { 1, 2, 3}, // list 1 of 1, 3, and 3 …
David.Chu.ca
  • 37,408
  • 63
  • 148
  • 190
290
votes
10 answers

Searching if value exists in a list of objects using Linq

Say I have a class Customer which has a property FirstName. Then I have a List. Can LINQ be used to find if the list has a customer with Firstname = 'John' in a single statement.. how?
Tony_Henrich
  • 42,411
  • 75
  • 239
  • 374
288
votes
4 answers

Select distinct using linq

I have a class list of class public class LinqTest { public int id { get; set; } public string value { get; set; } } List myList = new List(); myList.Add(new LinqTest() { id = 1, value = "a" }); myList.Add(new LinqTest() { id =…
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53