Get layer by name

1443
2
06-09-2020 12:17 PM
helenchu
Occasional Contributor II

Hi,

The codes below pick up the first layer.  If I want a layername instead of 1st.  How do I do that ?  Thank you!

// get the currently selected features in the map
var selectedFeatures = ArcGIS.Desktop.Mapping.MapView.Active.Map.GetSelection();

// get the first layer and its corresponding selected feature OIDs
var firstSelectionSet = selectedFeatures.First();

0 Kudos
2 Replies
Wolf
by Esri Regular Contributor
Esri Regular Contributor

The selection is returned as a Dictionary of MapMembers and the list of selected object ids for each MapMember.  In order words: Dictionary<MapMamber, List<long>>.  Once you know the inheritance relationship between MapMember and FeatureLayer (in essence that FeatureLayer inherits from MapMember) - this is from the online help:

you can now search the Dictionary returned by GetSelection for the specific FeatureLayer (or MapMember) you are looking for.  Below is a button click sample looking to the number of selected records in the 'TestPoints' layer.

protected override async void OnClick()
{
  var map = MapView.Active?.Map;
  if (map == null) return ;
  var layerName = "TestPoints";
  var searchThisLayer = map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(l => l.Name.Equals(layerName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
  if (searchThisLayer == null)
  {
    MessageBox.Show($@"Cannot find this layer: {layerName}");
    return;
  }
  var noIds = await QueuedTask.Run<List<long>>(() =>
  {
    // this returns a dictionary of MapMembers and a list of ObjectIDS for that MapMember's selection
    // Here is helps to know that a FeatureLayer inherits from BasicFeatureLayer, which inherits
    // from Layer, which inherits from MapMember
    // So if we are looking only for one FeatureLayer's selection then we can use 'searchThisLayer'
    // to check the return dictionary of MapMembers
    var listOfMapMemberDictionaries = MapView.Active.Map.GetSelection();
    if (!listOfMapMemberDictionaries.ContainsKey(searchThisLayer as MapMember))
    {
      // Selection Dictionary doesn't a 'searchThisLayer' MapMember 
      return new List<long>();
    }
    return listOfMapMemberDictionaries[searchThisLayer as MapMember];
  });
  MessageBox.Show($@"This layer: {searchThisLayer.Name} has {noIds.Count} selected items");
}
helenchu
Occasional Contributor II

Thank you very much Wolfgang.  It really helps.

0 Kudos