У меня есть файл CSV с необработанными данными, который я пытаюсь сопоставить с несколькими файлами, при сортировке мне нужно сопоставить коды учетных записей с их учетными записями.
Я использую List
из Account
и использую StartsWith
, чтобы попытаться сопоставить:
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; }
}
Они явно соответствуют первому Account
, есть ли способ сделать так, чтобы он соответствовал по порядку?
Обновленное решение:
Спасибо @ 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; }
}