gpt4 book ai didi

c# - 字符串以顺序开始

转载 作者:行者123 更新时间:2023-12-04 10:19:48 26 4
gpt4 key购买 nike

我有一个带有原始数据的 CSV 文件,我试图将其与多个文件匹配,在排序时我需要将帐户代码与其帐户匹配。

我正在使用 ListAccount并使用 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; }
}

最佳答案

您必须按代码长度对所有匹配项进行排序

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

关于c# - 字符串以顺序开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60910437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com