.NET Fiddle

CSharp · Console

/Program.cs

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

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

var pipeParser = new PipeParser();

var qryR02 = (QRY_R02)pipeParser.Parse(er7);


// Standard segments for QRY_R02 (v2.6)
// index: Name
//     0: MSH (Message Header)
//     1: SFT (Software Segment) optional repeating
//     2: UAC (User Authentication Credential Segment) optional
//     3: QRD (Original-Style Query Definition)
//     4: QRF (Original style query filter)

// Insert non-standard PID at index 4 (takes standard segment indexes into accoint)
// pushes QRF to index position 5
_ = qryR02.AddNonstandardSegment("PID", 4);
var pid = qryR02.GetStructure("PID") as PID;

pid.GetPatientIdentifierList(0).IDNumber.Value = "1234";
pid.GetPatientName(0).GivenName.Value = "John";
pid.DateTimeOfBirth.Value = "1970-01-10";
pid.AdministrativeSex.Value = "M";

// only replacing line endings so you can see result correctly on dotnetfiddle
var encoded = pipeParser.Encode(qryR02).ReplaceLineEndings();
Console.WriteLine(encoded);
;