I’m not a native C# programmer, however I do program in other languages such as PHP which is interpreted rather than compilied. Anyways…
In a lot of C# code we have had written for us I see code like this:
// Get value from Customer Part Cross Reference
foreach(var custxprt in (from ttrow in Db.CustXPrt.With(LockHint.NoLock)
where ttrow.Company == od.Company
&& ttrow.CustNum == od.CustNum
&& ttrow.PartNum == od.PartNum
&& ttrow.OtherField == od.OtherField
select new {ttrow.MyCustomField_c}) ) {
string myCustomValue = custxprt.MyCustomField_c;
}
The thing is we’re only expecting this CustXPrt record to have exactly one match. So I asked AI another way to get this record and it came up with this:
// Get value from Customer Part Cross Reference
var custxprt = (from ttrow in Db.CustXPrt.With(LockHint.NoLock)
where ttrow.Company == od.Company
&& ttrow.CustNum == od.CustNum
&& ttrow.PartNum == od.PartNum
&& ttrow.OtherField == od.OtherField
select new { ttrow.MyCustomField_c }).FirstOrDefault();
if (custxprt != null) {
string myCustomValue = custxprt.MyCustomField_c;
}
It seems a whole lot cleaner and straightforward. There is no foreach which I think in this instance. We don’t have to worry about closing the ending bracket (and indentation or lack thereof – I could go on for minutes about this topic) or other variables being in or out of scope because of the foreach structure, etc.
I’m curious to know, was the person who made the foreach just lacking in foresight to know how many records were to come back? I think we’ve got a copy-paste job cuz I see foreaches everywhere. It just feels like a lack of finesse / skill or copy-pasting laziness on the original programming.
Why are Epicor BPMs and their examples littered with foreaches when only one record is required? Why create all that extra code and programming overhead? I’m not sure maybe the compiler makes it more efficient in the background, I’m not too experienced with compiled languages.