如何从包含该字符串的对象中提取字符串?

时间:2019-10-24 09:30:25

标签: c# string object

我创建了一个Yaml,如下所示:

Directories:
    - ./Libraries:
        - DLLList.yml

    - ./Output:
        - None

现在,我将该Yaml反序列化为Objects列表:

List<object> allDirectoriesList = new List<object>();
List<string> allFileNames = new List<string>();

using (var reader = new StringReader(File.ReadAllText("./FileConfig.yml")))
{
    allDirectoriesList = deserializer.Deserialize<dynamic>(reader)["Directories"] as List<Object>;
}

foreach (var directory in allDirectoriesList)
{
    var directoryAsDictionary = (Dictionary<object, object>)directory;
    List<object> list = directoryAsDictionary.Select(kvp => kvp.Value).ToList();

    IEnumerable<string> _fileList = list.Select(i => i.ToString());

    List<string> fileList = _fileList.ToList<string>();

    for (int i = 0; i < fileList.Count(); i++)
    {
        var x = (string)list[i];
    }
}

directory是Dictionary类型的对象,在此部分中我将其转换为List:

var directoryAsDictionary = (Dictionary<object, object>)directory;
List<object> list = directoryAsDictionary.Select(kvp => kvp.Value).ToList(); 

list包含1个字符串类型的对象,文件名存储在该对象中。但是我无法从对象中获取这些字符串。如果我将其强制转换或将其转换为ToString(),我总会得到"System.Collections.Generic.List`1[System.Object]",但在这种情况下必须为"DLLList.yml"

1 个答案:

答案 0 :(得分:1)

假设您正在使用YamlDotNet

        List<object> allDirectoriesList = new List<object>();

        using (var reader = new StringReader(File.ReadAllText("./FileConfig.yml")))
        {
            allDirectoriesList = new DeserializerBuilder().Build().Deserialize<dynamic>(reader)["Directories"] as List<object>;
        }

        foreach (var directory in allDirectoriesList)
        {
            var directoryAsDictionary = (Dictionary<object, object>)directory;
            List<object> list = directoryAsDictionary.SelectMany(kvp => (List<object>)kvp.Value).ToList();

            List<string> _fileList = list.Select(Convert.ToString).ToList();

            foreach(var file in _fileList)
                Console.WriteLine($"Item: {file} found in {Convert.ToString(directoryAsDictionary.Keys.First())}");
        }

基本上,您试图将字典值转换为字符串,但这是一个列表。通过使用SelectMany,它可以将所有列表拼合为一个列表并使用它。有一些多余的演员表,我也删除了。为了将来参考,请尝试使您的结构尽可能简单,并将其反序列化为struct / classs-您会发现这种方法要容易得多。