Can Of Code

C# Quick LINQ example

Recently I’ve been working with LINQ so I thought i’d do a quick post to share the two basic LINQ approaches.

First up is an example of a query that returns a collection of objects. In this case they are RouteItem objects.

 

// The LINQ Query
var routesInDB = from RouteItem route in DB.routeItems select route;

// Populate a ObservableCollection with the query results.
routeItems = new ObservableCollection<RouteItem>(routesInDB);

 

The second example is for when you want to get one item from a query similar to “SELECT TOP 1” or  “SELECT … Limit 1” in SQL.

 

 // The LINQ Query
IQueryable<setting> cityQuery = from c in DB.setting where c.ID == 1 select c;

// populate the setting object with the query result.
setting sett = cityQuery.FirstOrDefault();

 

The example above shows the returning of a single setting object instead of a collection.

The final example shows how to get the number of results. This may be useful if you wanted to see if an item was already present in the collection.

 

// The LINQ Query
var query = from c in routeItems where c.routeName == "home" select c;

// get the size of the returned result set.
int size = new ObservableCollection<RouteItem>(query).Count;

 

This example shows a query to count how many RouteItems have the name “home”. We place the result into an int variable.

 

Leave a Reply

Your email address will not be published. Required fields are marked *