-2

我有字符串,我从如下文档中读取这些字符串:

IFCPERSONANDORGANIZATION

我的目标是创建一个名为相同的类的新实体。因此我需要这个字符串来匹配类名。但是,类名(我无法更改)如下所示:

IfcPersonAndOrganization

有什么方法可以更改该输入字符串,使其与大小写的类名匹配?

不幸的是,.ToTitle 不适用于我的目的,因为我的输入字符串中没有空格。但是,我确实有一个文本文件,其中包含所有可能的类名(~800)。所以我可能会写一个方法,检查匹配名称的文本文件并相应地更改我的输入字符串。恐怕这将花费很长时间并且效率很低。编辑:文本文件每行包含一个类名。

任何人都有一个可能更优雅和更快的想法?

4

1 回答 1

2

当然,您可以将文件内容读入列表,然后检查输入字符串是否包含在列表中(使用不区分大小写的比较)。如果是,您只需将字符串替换为列表中的字符串:

// The input string we want to format
var input = "IFCPERSONANDORGANIZATION";

// Read the file containing your class names into an array
var filePath = @"f:\public\temp\classnames.txt";
var knownClassNames = File.ReadAllLines(filePath);

// See if the list contains the name using a case-insensitive comarison. 
// If it does, `FirstOrDefault` will return a non-null value, so we assign the result
// Otherwise, if it returns null (which is checked by `??`) we leave it as is.
input = knownClassNames
    .FirstOrDefault(name => name.Equals(input, StringComparison.OrdinalIgnoreCase)) 
    ?? input;

这可以放入一个简单的函数中,您可以从任何地方调用它:

public static string CorrectClassNameCasing(string input)
{
    var filePath = @"f:\public\temp\classnames.txt";
    var knownClassNames = File.ReadAllLines(filePath);

    return knownClassNames
        .FirstOrDefault(name => name.Equals(input, StringComparison.OrdinalIgnoreCase)) ?? input;
}

对于我的示例,我创建了一个文件,其中仅包含您在示例中提到的一个类名:

static void Main()
{
    Console.WriteLine(CorrectClassNameCasing("IFCPERSONANDORGANIZATION"));
    Console.WriteLine(CorrectClassNameCasing("THISDOESNOTEXIST"));

    Console.Write("\nDone!\nPress any key to continue...");
    Console.ReadKey();
}

结果如下:

在此处输入图像描述

于 2017-08-07T19:12:38.130 回答