首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >字符串StartsWith顺序

字符串StartsWith顺序
EN

Stack Overflow用户
提问于 2020-03-29 05:15:38
回答 1查看 172关注 0票数 2

我有一个CSV文件与原始数据,我试图匹配多个文件,而排序,我需要匹配帐户代码与他们的帐户。

我使用List of Account并使用StartsWith来尝试和匹配:

代码语言:javascript
复制
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

代码语言:javascript
复制
 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; }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-29 05:25:42

您必须按代码长度排序所有匹配项。

代码语言:javascript
复制
accounts
    .Where(x => "5-4010".StartsWith(x.Code))
    .OrderBy(x => x.Code.Length)
    .LastOrDefault();
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60910437

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档