Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this LINQ query do?

Tags:

c#

linq

Here are two C# classes...

public class Address  
{  
    public string Country;  
    public string City;  
}

public class Traveller
{    
    public string Name;
    public List<Address> TravelRoute;
}

... and a list of data (filled somewhere) ...

List<Traveller> Travellers;

... and then this LINQ query:

var result = from t in Travellers
             where t.TravelRoute.Any(a => a.Country == "F")
             select t;

foreach (var t in result)
    System.Console.WriteLine(t.Name);

I do not understand the query: What means the "Any" function and what does the "=>" operator do?

Can someone explain me what's going on in this code? Thanks!

like image 921
Slauma Avatar asked Feb 10 '10 20:02

Slauma


People also ask

What is the purpose of a LINQ query?

LINQ simplifies this situation by offering a consistent model for working with data across various kinds of data sources and formats. In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, .

What do LINQ queries actually run?

LINQ queries are always executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution. You can also force a query to execute immediately, which is useful for caching query results.

Why do we need LINQ in C#?

LINQ in C# is used to work with data access from sources such as objects, data sets, SQL Server, and XML. LINQ stands for Language Integrated Query. LINQ is a data querying API with SQL like query syntaxes. LINQ provides functions to query cached data from all kinds of data sources.

What is LINQ and how when is it used?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.


1 Answers

It selects all travelers whose TravelRoute contains a country that is "F".

The Any functions returns true if any of the objects in the list satisfies the condition that is passed in to the function. From the method signature, you can see it takes a Func<> delegate that returns a bool. This means it takes any method that will return a boolean, including the lambda expression supplied.

This is different from Where, which will filter according to the condition that is passed in.

The => is a lambda expression. In this particular case, it is a shortcut to write an anonymous delegate.

like image 179
Oded Avatar answered Oct 12 '22 22:10

Oded