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
429
votes
2 answers

C# Linq Group By on multiple columns

public class ConsolidatedChild { public string School { get; set; } public string Friend { get; set; } public string FavoriteColor { get; set; } public List Children { get; set; } } public class Child { public string…
Kasy
  • 4,301
  • 2
  • 15
  • 6
424
votes
4 answers

Convert Linq Query Result to Dictionary

I want to add some rows to a database using Linq to SQL, but I want to make a "custom check" before adding the rows to know if I must add, replace or ignore the incomming rows. I'd like to keep the trafic between the client and the DB server as low…
Tipx
  • 7,367
  • 4
  • 37
  • 59
412
votes
7 answers

Preserving order with LINQ

I use LINQ to Objects instructions on an ordered array. Which operations shouldn't I do to be sure the order of the array is not changed?
Matthieu Durut
  • 4,838
  • 3
  • 20
  • 16
411
votes
15 answers

How to do SQL Like % in Linq?

I have a procedure in SQL that I am trying to turn into Linq: SELECT O.Id, O.Name as Organization FROM Organizations O JOIN OrganizationsHierarchy OH ON O.Id=OH.OrganizationsId where OH.Hierarchy like '%/12/%' The line I am most concerned with…
Matt Dell
  • 9,205
  • 11
  • 41
  • 58
403
votes
17 answers

Using LINQ to concatenate strings

What is the most efficient way to write the old-school: StringBuilder sb = new StringBuilder(); if (strings.Count > 0) { foreach (string s in strings) { sb.Append(s + ", "); } sb.Remove(sb.Length - 2, 2); } return…
tags2k
  • 82,117
  • 31
  • 79
  • 106
394
votes
7 answers

What does LINQ return when the results are empty

I have a question about LINQ query. Normally a query returns a IEnumerable type. If the return is empty, not sure if it is null or not. I am not sure if the following ToList() will throw an exception or just a empty List if nothing found…
David.Chu.ca
  • 37,408
  • 63
  • 148
  • 190
391
votes
5 answers

Flatten List in LINQ

I have a LINQ query which returns IEnumerable> but i want to return only List so i want to merge all my record in my IEnumerable> to only one array. Example : IEnumerable> iList = from number in (from no in…
Cédric Boivin
  • 10,854
  • 13
  • 57
  • 98
384
votes
11 answers

Remove duplicates in the list using linq

I have a class Items with properties (Id, Name, Code, Price). The List of Items is populated with duplicated items. For ex.: 1 Item1 IT00001 $100 2 Item2 IT00002 $200 3 Item3 IT00003 …
Prasad
  • 58,881
  • 64
  • 151
  • 199
356
votes
23 answers

How do I concatenate two arrays in C#?

int[] x = new int [] { 1, 2, 3}; int[] y = new int [] { 4, 5 }; int[] z = // your answer here... Debug.Assert(z.SequenceEqual(new int[] { 1, 2, 3, 4, 5 })); Right now I use int[] z = x.Concat(y).ToArray(); Is there an easier or more efficient…
hwiechers
  • 14,583
  • 8
  • 53
  • 62
355
votes
10 answers

How do you perform a left outer join using linq extension methods

Assuming I have a left outer join as such: from f in Foo join b in Bar on f.Foo_Id equals b.Foo_Id into g from result in g.DefaultIfEmpty() select new { Foo = f, Bar = result } How would I express the same task using extension methods?…
LaserJesus
  • 8,230
  • 7
  • 47
  • 65
355
votes
25 answers

Entity Framework. Delete all rows in table

How can I quickly remove all rows in the table using Entity Framework? I am currently using: var rows = from o in dataDb.Table select o; foreach (var row in rows) { dataDb.Table.Remove(row); } dataDb.SaveChanges(); However, it takes…
Zhenia
  • 3,939
  • 3
  • 15
  • 15
351
votes
9 answers

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

I have a list of objects that have two int properties. The list is the output of another linq query. The object: public class DimensionPair { public int Height { get; set; } public int Width { get; set; } } I want to find and return the…
theringostarrs
  • 11,940
  • 14
  • 50
  • 63
346
votes
16 answers

How would you do a "not in" query with LINQ?

I have two collections which have property Email in both collections. I need to get a list of the items in the first list where Email does not exist in the second list. With SQL I would just use "not in", but I do not know the equivalent in LINQ.…
Brennan
  • 11,546
  • 16
  • 64
  • 86
340
votes
12 answers

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

I know there are a few posts about Newtonsoft so hopefully this isn't exactly a repeat...I'm trying to convert JSON data returned by Kazaa's API into a nice object of some kind WebClient client = new WebClient(); Stream stream =…
J Benjamin
  • 4,722
  • 6
  • 29
  • 39
337
votes
21 answers

Using Linq to get the last N elements of a collection?

Given a collection, is there a way to get the last N elements of that collection? If there isn't a method in the framework, what would be the best way to write an extension method to do this?
Matthew Groves
  • 25,181
  • 9
  • 71
  • 121