Learn how to execute a SQL query to return features from a feature layer based on spatial and attribute criteria.

A feature layer can contain a large number of features stored in ArcGIS. You can query a layer to access a subset of its features using any combination of spatial and attribute criteria. You can control whether or not each feature's geometry is returned, as well as which attributes are included in the results. Queries allow you to return a well-defined subset of your hosted data for analysis or display in your app.
In this tutorial, you'll write code to perform SQL queries that return a subset of features in the LA County Parcel feature layer (containing over 2.4 million features). Features that meet the query criteria are selected in the map.
Prerequisites
Before starting this tutorial:
-
You need an ArcGIS Location Platform or ArcGIS Online account.
-
Ensure your development environment meets the system requirements.
Optionally, you may want to install the ArcGIS Maps SDK for .NET to get access to project templates in Visual Studio (Windows only) and offline copies of the NuGet packages.
Develop or download
You have two options for completing this tutorial:
Option 1: Develop the code
To start the tutorial, complete the Display a map tutorial. This creates a map to display the Santa Monica Mountains in California using the topographic basemap from the ArcGIS basemap styles service.
Open a Visual Studio solution
- Open the Visual Studio solution you created by completing the Display a map tutorial.
- Continue with the following instructions to execute a SQL query to return features from a feature layer based on spatial and attribute criteria.
Update the tutorial name used in the project (optional)
The Visual Studio solution, project, and the namespace for all classes currently use the name Display
. Follow the steps below if you prefer the name to reflect the current tutorial. These steps are not required, your code will still work if you keep the original name.
The tutorial instructions and code use the name Query
for the solution, project, and namespace. You can choose any name you like, but it should be the same for each of these.
-
Update the name for the solution and the project.
- In Visual Studio, in the Solution Explorer, right-click the solution name and choose Rename. Provide the new name for your solution.
- In the Solution Explorer, right-click the project name and choose Rename. Provide the new name for your project.
-
Rename the namespace used by classes in the project.
- In the Solution Explorer, expand the project node.
- Double-click MapViewModel.cs in the Solution Explorer to open the file.
- In the
Map
class, double-click the namespace name (View Model Display
) to select it, and then right-click and choose Rename....A Map - Provide the new name for the namespace.
- Click Apply in the Rename: DisplayAMap window that appears in the upper-right of the code window. This will rename the namespace throughout your project.
-
Build the project.
- Choose Build > Build solution (or press <F6>).
Add UI for selecting a predefined query expression
To make performing a query on a feature layer more flexible, add a Combo
control to present a list of predefined attribute queries for the parcels dataset. While editing this file, also modify the Map
control to bind its Selection
to a property in the view model (so you can set the color used to display selected parcels).
-
In the Visual Studio > Solution Explorer, double-click the MainWindow.xaml file to open it.
-
Add XAML that defines a
Combo
control and its behavior.Box - The control is positioned above the map view in the upper-left corner.
- A list of
Combo
s shows predefined expression choices.Box Item - The first combo box item instructs the user to choose an expression that will be selected when the app initializes.
- Changes in the selected expression will be handled by the
Query
event handler.Combo Box _Selection Changed
Also modify the
Map
control to bind theView Selection
property.Properties MainWindow.xamlUse dark colors for code blocks <Grid> <esri:MapView x:Name="MainMapView" Map="{Binding Map, Source={StaticResource MapViewModel}}" SelectionProperties="{Binding SelectionProps, Source={StaticResource MapViewModel}}"/> <ComboBox x:Name="QueryComboBox" SelectionChanged="QueryComboBox_SelectionChanged" SelectedIndex="0" SelectedValuePath="Content" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="20" Padding="30,10"> <ComboBoxItem>Choose a SQL where clause</ComboBoxItem> <ComboBoxItem>UseType = 'Government'</ComboBoxItem> <ComboBoxItem>UseType = 'Residential'</ComboBoxItem> <ComboBoxItem>UseType = 'Irrigated Farm'</ComboBoxItem> <ComboBoxItem>TaxRateArea = 10853</ComboBoxItem> <ComboBoxItem>TaxRateArea = 10860</ComboBoxItem> <ComboBoxItem>Roll_LandValue > 1000000</ComboBoxItem> <ComboBoxItem>Roll_LandValue < 1000000</ComboBoxItem> </ComboBox> </Grid>
-
In the section for the combo box you just added, right-click on the name of the event handler text ("QueryComboBox_SelectionChanged") and choose Go To definition from the context menu. Visual Studio will open the MapWindows.xaml.cs file with the stub for the new
Query
function.Combo Box _Selection Changed()
Add code to call the selected query for the current map extent
When the user chooses an expression in the combo box, call a function to execute the query.
The function to execute the query takes three arguments: the ID for the layer to query (string), a SQL expression that defines attribute criteria (string), and the area of the MapView
currently being viewed (Envelope
).
-
In the
Query
function: modify the method signature to add theCombo Box _Selection Changed() async
keyword.MainWindow.xaml.csUse dark colors for code blocks private async void QueryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { }
-
Again, in the
Query
function: add code to gather the information required to perform the query, then call theCombo Box _Selection Changed() Query
function (that you will write in a coming step).Feature Layer MainWindow.xaml.csUse dark colors for code blocks private async void QueryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { // Since the first choice in the combo box are instructions for the app // (not actual SQL where clause syntax), ignore it. if (QueryComboBox.SelectedIndex != 0) { // Get the view model using the ID given for the static resource in the XAML. var currentMapViewModel = this.FindResource("MapViewModel") as MapViewModel; // Get the current view point extent. var currentExtent = MainMapView?.GetCurrentViewpoint(ViewpointType.BoundingGeometry)?.TargetGeometry as Envelope; // Define the string ID for the feature layer to query. string featureLayerId = "Parcels"; // Define the SQL query where clause to apply to the feature layer. // Several SQL query strings were pre-populated in the combo box. // This line of code gets the selected choice from the combo box // and assigns it to the SQL query string. object selectedValue = QueryComboBox.SelectedValue; var sqlQuery = selectedValue?.ToString(); // Call the function in the view model that queries a feature layer. Pass in the: // (1) feature layer ID // (2) specific SQL syntax for the feature layer // (3) current map extent if (!string.IsNullOrEmpty(sqlQuery) && currentExtent != null) { await currentMapViewModel!.QueryFeatureLayer(featureLayerId, sqlQuery, currentExtent); } } }
Add the parcels layer to the map and set selection properties
You now need to begin working in a different code file within this project.
First, add the LA parcels FeatureLayer
to the map's collection of data layers (GeoModel.OperationalLayers
). Providing the Layer.Id
allows for referencing the parcels layer from the layer collection when needed. Define the selection color via the map view's SelectionProperties
to distinguish selected features in the map.
-
In the Visual Studio > Solution Explorer, double-click MapViewModel.cs to open the file.
The project uses the Model-View-ViewModel (MVVM) design pattern to separate the application logic (view model) from the user interface (view).
Map
contains the view model class for the application, calledView Model.cs Map
. See the Microsoft documentation for more information about the Model-View-ViewModel pattern.View Model -
Add additional required
using
statements at the top of the class. These make your code more concise and allow you to use classes from these namespaces without having to fully qualify them.MapViewModel.csUse dark colors for code blocks using System; using System.Collections.Generic; using System.Text; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using System.ComponentModel; using System.Runtime.CompilerServices; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.UI; using System.Threading.Tasks;
-
Just after the section of code that defines the
Map
public property, create a similarSelection
public property as follows.Props MapViewModel.csUse dark colors for code blocks private SelectionProperties? _selectionProps; public SelectionProperties? SelectionProps { get { return _selectionProps; } set { _selectionProps = value; OnPropertyChanged(); } }
-
Add code to the
Setup
function that adds the parcels feature layer to the map and sets the selection properties.Map() MapViewModel.csUse dark colors for code blocks private void SetupMap() { // Create a new map with a 'topographic vector' basemap. Map map = new Map(BasemapStyle.ArcGISTopographic); // Set the initial viewpoint around the Santa Monica Mountains in California. var mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84); map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000); // Set the view model's Map property with the map. Map = map; // Add a layer that shows parcels for Los Angeles County. Uri parcelsUri = new Uri("https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"); FeatureLayer parcelsFeatureLayer = new FeatureLayer(parcelsUri); // Give the layer an ID so we can easily find it later, then add it to the map. parcelsFeatureLayer.Id = "Parcels"; Map.OperationalLayers.Add(parcelsFeatureLayer); // Create selection properties (bound to the MapView). SelectionProperties selectionProps = new SelectionProperties(); selectionProps.Color = System.Drawing.Color.Yellow; this.SelectionProps = selectionProps; }
Create a function to query the parcels layer and select the result
In this step, create a new function that queries a FeatureLayer
(identified using its ID) using both attribute and spatial criteria. After clearing any currently selected features, a new query will be executed to find features in the map's current extent that meet the selected attribute expression. The features in the FeatureQueryResult
will be selected in the parcels layer.
-
Add the following new method named
Query
just after theFeature Layer() Setup
method.Map() MapViewModel.csUse dark colors for code blocks public async Task QueryFeatureLayer(string layerId, string whereExpression, Envelope queryExtent) { // Get the layer based on its Id. var featureLayerToQuery = _map?.OperationalLayers[layerId] as FeatureLayer; // Get the feature table from the feature layer. var featureTableToQuery = featureLayerToQuery?.FeatureTable; if(featureTableToQuery == null) { return; } // Clear any existing selection. featureLayerToQuery?.ClearSelection(); // Create the query parameters using the where expression and extent passed in. QueryParameters queryParams = new QueryParameters { Geometry = queryExtent, ReturnGeometry = true, WhereClause = whereExpression, }; // Query the table and get the list of features in the result. var queryResult = await featureTableToQuery.QueryFeaturesAsync(queryParams); // Loop over each feature from the query result. foreach (Feature feature in queryResult) { // Select each feature. featureLayerToQuery!.SelectFeature(feature); } }
-
Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app. If your app uses user authentication, enter your ArcGIS Online credentials when prompted.
The app loads with the map centered on the Santa Monica Mountains in California with the parcels feature layer displayed. Choose an attribute expression, and parcels in the current extent that meet the selected criteria will display in the specified selection color.
Alternatively, you can download the tutorial solution, as follows.
Option 2: Download the solution
-
Click the Download solution link in the right-hand panel of the page.
-
Unzip the file to a location on your machine.
-
Open the
.sln
file in Visual Studio.
Since the downloaded solution does not contain authentication credentials, you must first set up authentication to create credentials, and then add the developer credentials to the solution.
Set up authentication
To access the secure ArcGIS location services used in this tutorial, you must implement API key authentication or user authentication using an ArcGIS Location Platform or an ArcGIS Online account.
You can implement API key authentication or user authentication in this tutorial. Compare the differences below:
API key authentication
- Users are not required to sign in.
- Requires creating an API key credential with the correct privileges.
- API keys are long-lived access tokens.
- Service usage is billed to the API key owner/developer.
- Simplest authentication method to implement.
- Recommended approach for new ArcGIS developers.
Learn more in API key authentication.
User authentication
- Users are required to sign in with an ArcGIS account.
- User accounts must have privilege to access the ArcGIS services used in application.
- Requires creating OAuth credentials.
- Application uses a redirect URL and client ID.
- Service usage is billed to the organization of the user signed into the application.
Learn more in User authentication.
Create a new API key access token with privileges to access the secure resources used in this tutorial.
-
Complete the Create an API key tutorial and create an API key with the following privilege(s):
- Privileges
- Location services > Basemaps
- Privileges
-
Copy and paste the API key access token into a safe location. It will be used in a later step.
Set developer credentials in the solution
To allow your app users to access ArcGIS location services, use the developer credentials that you created in the Set up authentication step to authenticate requests for resources.
-
In Visual Studio, in the Solution Explorer, click App.xaml.cs to open the file.
-
Set the
ArcGIS
property with your API key access token.Environment. Api Key App.xaml.csUse dark colors for code blocks protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); // Set the access token for ArcGIS Maps SDK for .NET. Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.ApiKey = "YOUR_ACCESS_TOKEN"; // Call a function to set up the AuthenticationManager for OAuth. UserAuth.ArcGISLoginPrompt.SetChallengeHandler(); }
-
Remove the code that sets up user authentication.
App.xaml.csUse dark colors for code blocks protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); // Set the access token for ArcGIS Maps SDK for .NET. Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.ApiKey = "YOUR_ACCESS_TOKEN"; // Call a function to set up the AuthenticationManager for OAuth. UserAuth.ArcGISLoginPrompt.SetChallengeHandler(); }
Best Practice: The access token is stored directly in the code as a convenience for this tutorial. Do not store credentials directly in source code in a production environment.
Run the solution
Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app. If your app uses user authentication, enter your ArcGIS Online credentials when prompted.
The app loads with the map centered on the Santa Monica Mountains in California with the parcels feature layer displayed. Choose an attribute expression, and parcels in the current extent that meet the selected criteria will display in the specified selection color.
What's next?
Learn how to use additional API features, ArcGIS location services, and ArcGIS tools in these tutorials: