Search code examples
c#linq.net-framework-version

SELECT DISTINCT LEFT([string],2) in LINQ


I need to retrieve a distinct list of the left two characters of a string.

var result = work
            .Select(w =>  w.BillCode)
            .Distinct()
            .ToList();

I've gotten a distinct list using this linq statment, but I need the distinct list of 2 digit prefixes from the BillCode.

Instead of AB1, AB2, AB3, CD1, CD2, CD3... I need just AB, CD.

This is a legacy app stuck on .Net Framework 4.7.2.


Solution

  • var result = work
        .Select(w => w.BillCode.Substring(0,2))
        .Distinct()
        .ToList();
    

    Or, if your BillCode can have less than 2 chars:

    var result = work
        .Select(w => w.BillCode.Length>2 ? w.BillCode.Substring(0,2) : w.BillCode)
        .Distinct()
        .ToList();