Search code examples
c#visual-studiolinq

C# LINQ Substring


I am trying to join two of Programmes lists in Linq using the Programme Reference field in either list - the reference in List A may at times have "-R" appended at the end of it and may appear twice in the list (once with the "-R" and again without), whilst the references in List B will never have the "-R" appended at all.

In List A, there are two rows per record as already mention, and I am getting the "Length cannot be less than zero." error. Below is my code;

Examples are;

ListA
UG00001-2023
UG00001-2023-R
UG00002-2023
UG00002-2023-R

List B
UG00001-2023
UG00002-2023
var combinedList = from programmeA in ListA join programmeB in ListB on (programmeA?.REFERENCE.Substring(0,programmeA.REFERENCE.IndexOf("-R")) ?? programmeA.REFERENCE) equals programmeB?.REFERENCE ?? string.Empty
select new Programme()
{
...
}

So, what I am trying to achieve is that, if a row in Programme Ref in List A has "-R" appended at the end of the reference, return everything before the "-R", BUT if the Programme Ref does not have "-R" appended, then return the ref exactly as it is.

Any help would be appreciated.


Solution

  • The error you're encountering, "Length cannot be less than zero," is likely due to calling Substring or IndexOf on a string when the specified substring is not found. To avoid this error and achieve your desired result, you can modify your LINQ query as follows:

    var combinedList = from programmeA in ListA
        join programmeB in ListB
        on (programmeA.REFERENCE.EndsWith("-R")
            ? programmeA.REFERENCE.Substring(0, programmeA.REFERENCE.Length - 2)
            : programmeA.REFERENCE)
        equals programmeB.REFERENCE
        select new Programme
        {
            // project your properties here
        };
    

    This approach will handle the cases where the reference in List A may or may not have "-R" appended to it and join them accordingly.