var environment = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);
var prj = Project.Current;
var map = MapView.Active;
var defaultGDB = Project.Current.DefaultGeodatabasePath;
var featLayers = map.Map.Layers.OfType<FeatureLayer>();
var targetLayer = featLayers.ElementAt(0); // First layer in TOC
var joinLayer = featLayers.ElementAt(1); // Second layer in TOC
var outputFeatureClass = @"C:/temp/outputFC3.shp";
// Specify the field map in Spatial Join with target and join feature class/layers in the App
// Run Spatial Join manually - then Copy the fieldmap string from the result in Geoprocessing history and paste it for the fieldmap parameter.
// in this example of fieldmap, FireStations is the name of join layer
// FireStations layer has two numeric fileds (used in Fieldmap): TYPE and NUMBER - these two fields are used in the FiedlMap
//
var joinLayerName = joinLayer.Name;
var fieldMap = "TYPE 'TYPE' true true false 4 Long 0 0,Count,#,{joinLayerName},TYPE,-1,-1;NUMBER 'NUMBER' true true false 4 Long 0 0,Max,#,{joinLayerName},NUMBER,-1,-1";
var toolParameters = Geoprocessing.MakeValueArray(targetLayer, joinLayer, outputFeatureClass, "JOIN_ONE_TO_ONE", "KEEP_COMMON", fieldMap, "INTERSECT");
GPExecuteToolFlags executeFlags = GPExecuteToolFlags.AddOutputsToMap | GPExecuteToolFlags.GPThread | GPExecuteToolFlags.AddToHistory | GPExecuteToolFlags.RefreshProjectItems;
IGPResult gpResult = await Geoprocessing.ExecuteToolAsync("analysis.SpatialJoin", toolParameters, environment, null, null, executeFlags);
Geoprocessing.ShowMessageBox(gpResult.Messages, "GP Messages", gpResult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);