Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Everything / LINQ

LINQ

LINQ

Great Reads

by Felice Pollano
Listed here are 5 interesting uses of Linq.Expression without writing a LinqToSomething provider, of course.
by Paul_Wade
A WPF application for viewing RSS video feeds. Built using the MVVM pattern.
by Pranay Rana
(Linq and Nullable Values) OR (SQL ISNULL with LINQ)
by #realJSOP
Don't reinvent the wheel - use the one that's already on the cart.

Latest Articles

by Felice Pollano
Listed here are 5 interesting uses of Linq.Expression without writing a LinqToSomething provider, of course.
by Paul_Wade
A WPF application for viewing RSS video feeds. Built using the MVVM pattern.
by Pranay Rana
(Linq and Nullable Values) OR (SQL ISNULL with LINQ)
by #realJSOP
Don't reinvent the wheel - use the one that's already on the cart.

All Articles

Sort by Score

LINQ 

by Pranay Rana
(Linq and Nullable Values) OR (SQL ISNULL with LINQ)
by #realJSOP
Don't reinvent the wheel - use the one that's already on the cart.
by TheGreatAndPowerfulOz
The following is far easier to understand and use than the Outlaw's tip (IMHO).text = Regex.Replace(text, "screen_fadetimeout=\"[^\"\']+\"", "screen_fatetimeout="99");It has the following advantages:1. It is one line of code2. It is easier to read3. It is faster (note: XmlElement...
by Yaseer Mumtaz
.NET interview questions and answers with real world examples and code snippets
by Michael Bogaerts
What brings the 15.2 release for XAF (win) developers
by Lee Humphries
LINQ translates .count() to a SQL query that uses COUNT(*), but on large tables even count(*) can be too slow. Here's another way
by basementman
Or, assuming your table has an index, you could do this "old-school" as:select MAX(rows) from sysindexes where id = Object_ID('{tablename}')
by shijo joseph
An ADO.NET Layer for SQL Server and Oracle which makes it easier for interfacing with database
by Marlon Hizole
An elegant approach to pagination
by Basem AlShabani
How to solve recurring problems using LINQ
by sumit_kapadia
AutoComplete Texbox with comma separated insertions
by Eduardo Yost
Creating a Web User Control containing an AutoCompleteExtender for data through WCF (JSON) allowing to store the entity selected through EntityFramework. Entity object serialization from the server to the client and the client to the server.
by Alberto Nuti
How to serialize an object without having to manually instruct the DataContractSerializer class.
by Kundan Singh Chouhan
Simplest, best and most robust architecture.
by Bhushan Mulmule
This is terribly unorganized document with mix of MVC, Entity Framework, LINQ, HTML 5 and JQuery how tos...
by Ramesh Bevara
An overview of a helper class to build dynamic order by clause in LINQ query in C#
by Fitim Skenderi
Build where clause dynamically in Linq
by DiponRoy
Let's make a lambda expression from a property name of a particular entity, and use it for OrderBy shorting
by Clifford Nelson
This tip provides examples of how to use the different arguments of the Linq GroupBy extension method.
by Houssem Dellai
Developing a Windows Phone app step by step
by Mathi Mani
In this tip, we will see how to perform case sensitive comparison of datatables using LINQ
by Thomas Daniels
In this tip, I tell you how to cast an IEnumerable to an IEnumerable(T)
by Daniel Ziegelmiller
How to track changes in the ObservableCollection displayed in a WPF DataGrid
by suhas.shiv
Custom CheckBoxList in ASP.NET MVC3
by Physlcu$
A custom ComboBox that supports live filtering of items by Substring-Search or any other Lamda-Expression
by Rami Shareef
Sometimes you need the Linq query result as datatable (I need it today)Use this: public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query) { if (query == null) { throw new ArgumentNullException("query"); ...
by jonx
Very good stuff. Learned me a lot about how to access to the physical structure of the query.There is also a CopyToDataTable : http://msdn.microsoft.com/en-us/library/bb386921.aspx[^]And for the record here is a C# version:protected DataTable EntityToDatatable(IQueryable Result,...
by Naufel Basheer
Convert complex XML to an object using LINQ
by Mikhail-T
A short one-line way to convert Array or List of any data into custom string via LINQ
by Namlak
string blah = string.Join(",", cities.Select(c=> c.Name));
by wgross
I would just use:string.Join(",", cities.Select(c=>c.Name))Since Version 4 of the Framework there is an overloaded versions of string.Join for IEnumerable too. It uses a StringBuilder internally and doesn't insert a seperator after the last element as well.I could't find the Join method...
by Richard Deeming
If you're stuck with .NET 3.5, you can use the Aggregate extension method[^]:string cities_string = cities.Aggregate(new StringBuilder(), (sb, c) =>{ if (0 != sb.Length) sb.Append(", "); sb.Append(c.Name); return sb;}, sb => sb.ToString());
by The Manoj Kumar
Did you ever face a situation where you want to calculate total number of occurrences of a value in a List object?What approach did you used for it?Did you ever try LINQ for the same? Yes, you can use it. Just look at the example below:class Program{ static void Main() ...
by SuhasHaridas
Create Linq to SQL connection with select, insert, delete, update
by Carlos Conceição
This article how you can use TextToCalcExpression to generate Linq Expressions in runtime
by HUONG Minh-Luong
How to use PresentationMapper to generate presentation objects
by Indresh_Prajapati
This tip will help beginners to implement CRUD operations in ASP.NET MVC 4 with scripting language as KnockOut and Database as MS SQL 2008R2.
by Wendelius
This tip describes few examples how ro cumulate values using an extension method with LINQ
by Wendelius
This is an alternative for "Cumulating values with LINQ"
by Matt T Heffron
This is an alternative for "Cumulating values with LINQ"
by Vishnu Kesaraju
Using LINQ to XML to convert datatables to formatted XML.
by Pranay Rana
DataLoadOptions and How to use in Compiled Linq query
by Jaume González
How to convert any datareader into generic list.
by karenpayne
This code permits a developer to determine if a radio button is selected in a container such as a panel or GroupBox using syntax similar to TryParse.Requires Requires Framework 3.5 or higherExamplePrivate Sub Button1_Click() Handles Button1.Click Dim SelectedButton As New...
by Sunil_Sebastian
Duplicate Notifier for a List using ObservableCollection.
by Maninder Singh Puhi
Appropriate query to fetch required no of results from DB instead of getting all at on time for binding controls like Gridview, listview etc
by Thomas Corey
Dynamically sort query results using LINQ expressions and reflection.
by oryan
Dynamically build Linq2Sql classes based off SQL table
by Randy Kroeger
Created a POC that dynamically builds a predicate using Expression and Reflection.
by Elvis Begluk
Dynamically generate LINQ query with a custom property.
by ravgill66
Use LINQ to XML to split an XML file into a number of smaller files
by Max Vagner
Converting mainframe EBCDIC to ASCII format
by dan!sh
A simple way to edit a list or collection which is iterated in a foreach loop
by Robert Lindblom
Removing entity if it exists
by Sarvesh Kushwaha
Binding Gridview (or any other data control) with effective paging using LINQ
by Brady Kelly
A quick and easy way to ensure that your Code First DB Initializer is always run when your app starts, not just on the first data access operation
by Debopam Pal
How to bring data from Entity model to Excel file using LINQ.
by Alen Toma
EntityWorker.Core - an alternative to entity Framework
by Sarvesh Kushwaha
Export Excel to SQL database table (Sample Code)
by Yuriy Anisimov
Expressmapper - lightweight, lighting fast and easy to use .NET mapper
by Pranay Rana
Extended ORM generated class
by Rishikesh_Singh
Filtering records from List similar to Sql IN Operator using LINQ
by Rajesh Kariyavula
Find the Odds Out in A Generic List
by Midi_Mick
Use LINQ to get the members of a collection that match the members of another collection
by Vahid_N
It's easy to forget not disposing object contexts, which leads to memory leaks and also leaves too many related connection objects not disposed as well.
by scott_liu
Entity Framework Core client evaluation was disabled by default since version 3.0 because of performance.
by João Matos Silva
FlatMapper is a library to import and export data from and to plain text files
by Yves Vaillancourt
Adding an extension method to LINQ to flatten any hierarchical collection
by CodingLover
How to format unformatted XML string easily with LINQ.
by User-Rock
LINQ to SQL
by Andre van Dun
Generate game list based on list of players in C#
by Md._Mehedi_Hasan
This tip will help you to generate .xml file in AngularJs and ASP.NET MVC5 using XElement of C#.
by Michael Agroskin
Many LINQ functions have a hidden parameter useful to generate or analyze sequential indices
by murtaza dhari
A generic dropdown control using LINQ to SQL and Entities using Reflection
by Paul Brower
This tip will allow you to return the value from column X, where column Y matches your filter
by vijay__p
How to perform CRUD operations using generic repository with EF pattern with and dependency injection.
by Delashmate
Deep Look in the basics of LINQ
by BillWoodruff
Create collections of #n sized elements from arrays, lists, and string
by moosa pourghafari
Get LINQ GetCommand parameters.
by Massimiliano Peluso "WeDev Limited"
Get Nested Property value using reflection and Linq.Expression
by cechode
Saw this a while back; it's simpler (dirty and wrong but... ):public static T Get(Func getDelegate, bool DefaultTOnNull = false, T defaultVal = null) where T : class{ T result = null; try { result = getDelegate(); } catch...
by karenpayne
Returns all checked Checkbox controls in a Windows Form container
by Gregory Gadow
With LINQ, you can retrieve an enumeration's metadata, such as its minimum and maximum values and whether it contains a given value.
by Arun Jacob
Sometimes we want to compare the property names like,if (e.PropertyName == "FirstName"){//Do Something}But this is not type safe. If we change the property name then this won’t work as expected and also it won’t throw compile time error. For getting property name for Type safe...
by Dev_2580
For the last couple of days, working on my project for my studies I have struggled with this annoying issue regarding LINQ to SQL classes.When we update an entity within a DataContext, we can simple use something likecontext.Entity.Attach(updatedEntityInstance)The proplem is that...
by Milad Ashrafi
We need this script for database based ASP.NET websites for using HTML content in post pages.
by debolina.d
Limit the number of records that can be fetched from database based on its count like using the LIMIT clause in MySql
by debashishPaul
How to convert LINQ query to DataTable
by -james
Iterate through the results and extract using system.reflection
by Ed Nutting
How to fix LocalDB / SQL Server: "Cannot open database "XYZ" requested by the login. The login failed. Login failed for user ABC"
by karimbaig5
This tip provides an idea about how to insert a record into a table having no primary key using LINQ to SQL.
by Pranay Rana
Log your LINQ query
by jim lahey
I prefer to use ToTraceString() on the ObjectQuery:http://msdn.microsoft.com/en-us/library/system.data.objects.objectquery.totracestring.aspx[^]It's less intrusive as I don't have to instantiate and dispose the StreamWriter and I have more control over where and how I log the resultant...
by The Myth
How to return Json in VB.NET in multiple ways
by EuGenius_Krivbass
Today I was trying to save list of entities those were generated by DBMLThis code shows how you can store your list in XML string and put it in ViewState, after that you get your list back.Using the CodeYou can use this code as you need.Here is class Serializatorpublic class...
by maq_rohit
How to set the connection string in your LINQ dbml file dynamically based on web.config
by Arun Jacob
In LINQ to SQL the relational data is loading only when we refer that data, other terms its lazy loading of data.But we can load relational data ,suppose we have an Employee Table and also having an Employee details table related to Employee Table, we can load that relational data using...
by gardnerp
This tip shows how to import XLS data to a SQL database using Link to SQL.
by Tony Sherlock
Snippet for Left Outer Join, Entity Framework
by Juan Francisco Morales Larios
Let in LINQ
by dgDavidGreene
Helper utility replaces magic string property names.
by Srinivasu Pemma
This tip provides an easy way of dealing with different types of data sources for LINQ Group By taken from my blog http://www.srinetinfo.com/2012/12/linq-group-by.html
by TalentTuner
In this article, We will perform basic linq operations using LINQ To Objects and LINQ To Entity
by Programm3r
I sometimes get asked how to get a single object from a generic list based on a LINQ query. i.e. Performing a LINQ query on a generic collection and then returning only the single instance without looping through the collection. Well this is how I do it:public class Person{ public...
by Ryszard Dżegan
How to take full advantage of declarative paradigm by using LINQ.
by Uladzislau Baryshchyk
Basics of the embedded LINQ language
by Pranay Rana
To understand how execution take place consider below code: //Query not going to execute at this pointvar query = from customer in db.Customers where customer.City == "Paris" select customer; Most of the people think that the query gets...
by Hisham Abdullah Bin Ateya
LINQ Extensions methods that may help you a lot
by Super Lloyd
Adding LINQ goodness to Javascript?
by Delashmate
Notes regarding LINQ abstraction.
by Pranay Rana
Linq Joins with SelectMany
by Steven Oberholzer
The following tip contains a simple way to get an array of month names. It is a one liner, a rather trivial task - but I thought it was too cool not to share :).
by Mohd Manzoor Ahmed
Linq Queries Examples Using Method And Query Syntax
by Winstan
Case sensitive LINQ query
by Hisham Abdullah Bin Ateya
LINQ to CSV files.
by Mr Orange
Introduction...
by Jaume González
Extends Arrays in JavaScript, adding the main domain and filtering functions of LINQ
by A Mahesh
LINQ to SQL – Execute SQL Queries
by Hiren Khirsaria
Mapping Stored Procedure with DBML to get multiple results from Stored Procedure
by Ehtesham Mehmood
LINQ to SQL using C#
by aboubkr90
A way around "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities"
by David_Wimbley
How to make a comma separated string using Linq
by Phil Martin
This does the same as Enumerable.Max(), but allows for a second function to select the result, rather than returning the usually useless score./// /// Transforms each item of the sequence to a double score using the function, and finds the maximum scored...
by e.bonavero-miller
make sure that web.config contains these config sections: ...
by A. Fry
MonogoDB server side projection using the C# driver
by Pritam Deshmukh
This tip elaborates few useful tricks and shortcuts of VS 2013 mainly for professional edition (You can find them with Ultimate version too).
by Sion Cohen
An elegant programmatic solution for having multiple indexers in C#
by VijayRana
Some useful MVC Attributes (Bind Attribute, HandleError Attribute, HiddenInput Attribute, Remote Attribute)
by karenpayne
Using newer conventions of coding in VS2010 and higher
by Csaba Fábián
An open source library of Linq operators on ObservableCollection
by me.ajaykumar
OData
by taha bahraminezhad Jooneghani
Problem around .first() method in EF and a good solution
by mohammad amiri
Paging DataGridView using LINQ in C#.
by Avinash Narnaware
How to create Pivot Table in SQL Server 2008 R2 and in C# Linq to Entity Framework in a step by step manner with two different instances.
by Member 3531622
Get rid of trivial mapping between objects like mapping between obj1.City and obj2.Town or between properties with the same name
by Wendelius
This tip shows one way to query hierarchical data from a DataTable by using an AsTree() method.
by HemendraSingh88
Hi, here we will see how to query a DataSet with LINQ(Language Integrated Query).
by Gunaprasad Shetty
The tip provides the code snippet for inserting a huge XML file with details such as node level, node value, node desc and node child, etc.The snippet provides the solution for recursive reading of node and provides the value of XML nodes along with its value.
by John L. Vidal
Know how an event in your app is performing by using Reactive Extensions
by Rafael Nicoletti
Refactor C# code to become more expressive
by karenpayne
This VS2008 or higher extension uses a LINQ statement to remove duplicate items from a string array but is not case sensitive, also you might like to leave the sort/order-by in the extension or remove it.ExampleDim Names() As String = {"Bob", "Mary", "bob", "Bob", "Jane", "Kevin",...
by Delashmate
Advantages of replacing a foreach loop with LINQ
by George Swan
Isn't it possible to remove the from and select statements by using a lambda expression?var bestStudents=students.Where(s=>s.Grade>9);
by Shmuel Zang
For replacing foreach loop, for a non-query operation, just for performing an operation on each element in the collection, we can use the ForEach method, like the following:students.ToList().ForEach(s => { s.Grade += 10;});
by Ashley Davis
The technique presented here is a simple method of resampling and aggregating time series.
by Nithila Shanmugananthan
Re-usability of view in MVC
by DerStauner
With this library it is possible to query datatables with SQL commands.
by Dario Picca
Save Key and Value in JSONformat using C# and LINQ
by yrimal
How to search XML content using LINQ in .NET.
by MarkLTX
When using LINQ to SQL, it can be very useful to see the SQL commands that are generated by your LINQ expressions. Sometimes the results are surprising and you might be able to improve performance by tweaking the LINQ.All you have to do is set the Log property of the DataContext object. ...
by Henry Minute
Or, there's always Scott Guthrie's LINQ To SQL Debug Visualizer[^].[Edit]While I'm posting links there is a nice utility that can output the generated SQL to the Debug Window in VS written by Kris Vandermotten.You can get it here[^].To use it: MyDataContext db = new...
by Philippe Mori
LINQPad is an interesting tool to try queries.LINQPad[^]Perfect tool to try out some alternatives for complex queries. As we can see generated queries and elapsed time, it help a lot to help having fast queries for complex requests.
by AspDotNetDev
If you are the type that likes to debug production code, you can use SQL Profiler to find queries generated by your LINQ statements. This is a technique I recently used because it was so simple and did not require me to recompile anything.Note that StefanHam already posted this alternate...
by Magnus_
An extension method to the IEnumerable`1 interface that can select all children recursively of an entity in a tree like structure
by John Adams
Magnus, I really like the idea! I believe your original idea (posted @ http://www.codeproject.com/KB/linq/LinqToTree.aspx) is even better for the general case - probably better than the solution in the article - it does feel more generic while still being very easy to use.I'm sure you may...
by Eric Shandil
How to get dictinct records from a datatable in .NET.
by Alexandre Paula
aspnet Membership Login in any project you want.
by Ahmad F Hassan
Step by step, creating LINQ to SharePoint Data Access Layer using SPMetal
by Dav Zen
Simple and easy to use jQuery matrix 2D.
by Sharp Ninja
Threading can be a daunting topic. This library takes much of the worry (and mistakes) out of multi-threaded application programming.
by George Jonsson
LINQ methods can be slow inside loops as this little demo shows.
by Itai Basel
Finally found a solution to the annoying LINQ to SQL dbml error: CS0029 : Cannot implicitly convert type 'int' to 'System.Data.Linq.Link'.
by Kevin Marois
This simple extension method allows you to create a SortedSet from a Linq query
by Matt T Heffron
Since SortedSet has a constructor that takes an IEnumerable parameter, the ToSortedSet extension method can be greatly simplified:public static SortedSet ToSortedSet(this IEnumerable t){ return new SortedSet(t);}
by Bhis
Various ways to sort list and compare results
by JP_Rocks
A tip to concatenate a set of strings using comma/pipe
by Mohammad A Rahman
The idea was good, but I think we could probably do something like below:public static string UsingStringJoin(IEnumerable sList, string separator){ return sList.Any() ? string.Join(separator, sList.ToArray()) : string.Empty;}public static string...
by Mario Majčica
Or even better:public static string Join(this IList list, string joinString) { StringBuilder result = new StringBuilder(); int listCount = list.Count; int listCountMinusOne = listCount - 1; if (list != null && listCount > 0) { ...
by Erich Ledesma
I rather like IEnumerable than IList, parameters should be as general as posible. I think it's really getting very fun up here. Here's my choice, just for strings.public static string Join(this IEnumerable parts, string separator){ if (! parts.Any()) return...
by George Swan
You can use the Aggregate method with a StringBuilder. I've modified Eric's alternative in order to save a bit of code. Only one return statement is needed as an empty StringBuilder returns an empty string.public static string Join(this IEnumerable parts, string separator) { ...
by Matt T Heffron
This is an alternative for "Subset - Sum Problem with Integer Arrays "
by Erol Esen
This tip uses the elegant LINQ to solve pesky daily problems.
by PIEBALDconsult
This is an alternative for "The Elegant Art of Programming"
by PIEBALDconsult
This is an alternative for "The Elegant Art of Programming"
by Guillaume Leparmentier
This is an alternative for "The Elegant Art of Programming"
by Juan Pablo G.C.
This is an alternative for "The Elegant Art of Programming"
by Toby Steed
Walk before you can run
by puja11191
This tip shows how can we generate and save XML files
by Bilel Msekni
How to transform a list to a dictionary in 3 different ways?
by Jaime Olivares
Workaround to mimic VB.net's Xml Literals in C#
by Dan Avidar
Lambda expressions short tutorial
by Mr.PoorEnglish
This is an alternative for "Understand Lambda Expressions in 3 minutes"
by Mannava Siva Aditya
Uploading multiple files and creating a Zip file in ASP.NET with C#.
by _Noctis_
How to avoid some hardcoded paths with the uses of Environment.UserName
by Ismael Almonte
Use basic LINQ commands to manipulate and query .net objects.
by Roger C Moore
This tip is a guide for using the Codeplex project Effort for testing Entity Framework applications without requiring the unit tests to actually hit the SQL Server database.
by #realJSOP
Extension methods can help you avoid sticky situations.
by Rama Krishna Vavilala
I will just make it a little more compact by omitting the Contains method:public static string GetValue(this XElement root, string name, string defaultValue) { return (string)root.Elements(name).FirstOrDefault() ?? defaultValue; }The explicit operators for XElement...
by Richard Deeming
You can avoid all of this by using the explicit cast operators:public XElement Element{ set { this.MyVar1 = (string)value.Element("MyVar1") ?? "NO VALUE"; this.MyVar2 = (string)value.Element("MyVar2") ?? "NOVAL"; }}Both XElement and XAttribute define...
by Richard Deeming
This is an alternative for "Using Extension Methods To Avoid XML Problems"
by The Manoj Kumar
Did you ever face a situation where you want to read a delimited file (CSV or any similar format) and want to filter the records on the basis of some conditions (by checking some values against columns).For example, let's assume that Data.txt file contains the following...
by Måns Tånneryd
This tip shows how to significantly speed up inserts of large amounts of data using the entity framework.
by Måns Tånneryd
This tip shows how to speed up inserts using POCO objects and the entity framework version 5.
by Måns Tånneryd
How to use bulk insert with your LINQ-to-SQL datacontext
by RupertC
If the order of your columns is different in the LINQ to SQL class from that in the database, then you also need to add a column mapping to the bulk copier. Otherwise you get mysterious errors in some of the loaded columns!In my simple fix, I assume that the names match even if the order may...
by Christ Akkermans
Code for verifying the resources used by DisplayAttribute in order to catch any missing resource strings
by xibao
Generate class definition for Web API Service Models.
by ravichaitanya.m
The code shown here allows a user to get all public tweets of her /his liking without logging into Twitter and search for tweets with keywords. It also allows the user to search for his/her friends who are tagged in his/her albums.
by Tony Dubey
This code demonstrate pros and cons of PLINQ as compared to LINQ
by Andreas Gieriet
How Linq extension methods benefit from interfaces inheriting from interfaces
by ShaikAnwar
This topic gives us an idea of how to write Linq queries on Entities & DataTable. This covers some basic querying and also usage of joins and group by using LINQ.
by Oussama_Kahoul
Introduction to WPF technology and the MVVM design pattern
by Dariush Tasdighi
A very powerful and customizable source code that converts the Infix to Postfix expression.