Search code examples
c#stringstartswith

String StartsWith Order


I have a CSV File with Raw Data which I'm trying to match with multiple files, while sorting I need to match account codes to their accounts.

I'm using a List of Account and using StartsWith to try and match:

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var accounts = new List<Account> { 
            new Account {
                Id = 9,
                Code = "5-4",
                Name = "Software",
            }, 
            new Account {
                Id = 10,
                Code = "5-4010",
                Name = "Hardware"
            } 
        };

        var hardwareAccount = accounts.FirstOrDefault(x => "5-4010".StartsWith(x.Code));
        Console.WriteLine(hardwareAccount.Name); // Prints Software - Should be Hardware

        var softwareAccount = accounts.FirstOrDefault(x => "5-4020".StartsWith(x.Code));
        Console.WriteLine(softwareAccount.Name); // Prints Software - Correct
    }
}

public class Account {
    public int Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

They are obviously matching the first Account, is there a way to make it match in order?

Updated Solution:
Thanks @SirRufo

 class Program
    {
        static void Main(string[] args)
        {
            var accounts = new List<Account>
            {
                new Account
                {
                    Id = 9,
                    Code = "5-4",
                    Name = "Software",
                },
                new Account
                {
                    Id = 10,
                    Code = "5-4010",
                    Name = "Hardware"
                }
            }.OrderBy(x => x.Code.Length);

            var hardwareAccount = accounts.LastOrDefault(x => "5-4010".StartsWith(x.Code));
            Console.WriteLine(hardwareAccount.Name);

            var softwareAccount = accounts.LastOrDefault(x => "5-4020".StartsWith(x.Code));
            Console.WriteLine(softwareAccount.Name);

            Console.ReadKey();
        }
    }

    public class Account
    {
        public int Id { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
    }

Solution

  • You have to order all matches by the code length

    accounts
        .Where(x => "5-4010".StartsWith(x.Code))
        .OrderBy(x => x.Code.Length)
        .LastOrDefault();