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!
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, .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With