我有一个包含原始数据的CSV文件,该文件试图与多个文件匹配,而排序时我需要将帐户代码与他们的帐户进行匹配。
我正在使用List
ofAccount
并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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句