.NET Fiddle

CSharp · Console

/Program.cs

using System;
using NHapi.Base.Parser;
using NHapi.Base.Model;
using NHapi.Model.V26.Message;
using NHapi.Model.V26.Datatype;

var er7 = """
	MSH|^~\&||KC1234F3|||20230810160302+0800||QRY^R02|202308101603020042|P|2.6
	QRD|20230810160302+0800|R|I|Q101||||TXE107200400230|RES
	PID|||107200400230||Surname^Lastname|||M||||||||||107200400230
	PV1||I|^^&1
	QRF|MON||||168430091&5^5^1^0^2005&2005&2005&2005&2005
	""".ReplaceLineEndings("\r");
	
var pipeParser = new PipeParser();

var qryR02 = pipeParser.Parse(er7) as QRY_R02;
ST part5 = qryR02.QRF.GetOtherQRYSubjectFilter(0);

// getting non existant at index 4 component will create it
var newComponent = part5.ExtraComponents.GetComponent(4);
((GenericPrimitive)newComponent.Data).Value = "test";

// getting non existant sub component at index 0 will create it
var newSubComponent = newComponent.ExtraComponents.GetComponent(0);
((GenericPrimitive)newSubComponent.Data).Value = "subcomponent";

Console.WriteLine(PipeParser.Encode(qryR02.QRF, EncodingCharacters.FromMessage(qryR02)));
;