为什么return是List<char>?

Why is the return is List<char>?

我正在尝试使用 "contains" 方法提取与子字符串匹配的文件名。然而,return 似乎是 List<char> 但我期望 List<string>

private void readAllAttribues()
{
    using (var reader = new StreamReader(attribute_file))
    {
        //List<string> AllLines = new List<string>();
        List<FileNameAttributeList> AllAttributes = new List<FileNameAttributeList>();

        while (!reader.EndOfStream)
        {
            FileNameAttributeList Attributes = new FileNameAttributeList();
            Attributes ImageAttributes = new Attributes();
            Point XY = new Point();
            string lineItem = reader.ReadLine();
            //AllLines.Add(lineItem);
            var values = lineItem.Split(',');

            Attributes.ImageFileName = values[1];
            XY.X = Convert.ToInt16(values[3]);
            XY.Y = Convert.ToInt16(values[4]);
            ImageAttributes.Location = XY;
            ImageAttributes.Radius = Convert.ToInt16(values[5]);
            ImageAttributes.Area = Convert.ToInt16(values[6]);
            AllAttributes.Add(Attributes);
        }
        List<string> unique_raw_filenames = AllAttributes.Where(x => x.ImageFileName.Contains(@"non")).FirstOrDefault().ImageFileName.ToList();
        List<string>var unique_reference_filenames = AllAttributes.Where(x => x.ImageFileName.Contains(@"ref")).FirstOrDefault().ImageFileName.ToList();


        foreach (var unique_raw_filename in unique_raw_filenames)
        {
            var raw_attributes = AllAttributes.Where(x => x.ImageFileName == unique_raw_filename).ToList();

        }
    }
}

数据类型class

public class FileNameAttributeList
        {   // Do not change the order
            public string ImageFileName { get; set; }
            public List<Attributes> Attributes { get; set; }

            public FileNameAttributeList()
            {
                Attributes = new List<Attributes>();
            }
        }

为什么 FirstOrDefault() 不起作用? (它 returns List<char> 但我期待 List<string> 但失败了。

ToList()方法将实现IEnumerable<SomeType>的集合转换为列表。 查看Stringdefinition,可以看到它实现了IEnumerable<Char>,所以下面代码中的ImageFileName.ToList()会return一个List<char> .

AllAttributes.Where(x => x.ImageFileName.Contains(@"non")).FirstOrDefault().ImageFileName.ToList();

虽然我在猜测您想要什么,但您似乎想根据 ImageFileName 过滤 AllAttributes,然后获取这些文件名的列表。如果是这样的话,你可以使用这样的东西:

var unique_raw_filenames = AllAttributes.Where(x => x.ImageFileName.Contains(@"non")).Select(y=>y.ImageFileName).ToList();

在你的代码中

List<string> unique_raw_filenames = AllAttributes.Where(x => x.ImageFileName.Contains(@"non")).FirstOrDefault().ImageFileName.ToList();

FirstOrDefault() returns AllAttributes 列表中的第一个或默认 FileNameAttributeList,其中 ImageFileName 包含文本 non。 在 ImageFileName 上调用 ToList() 然后将字符串值转换为字符列表,因为字符串是字符的集合。

我认为将 FirstOrDefault 切换为 Select 可以实现您的意图。 Select 允许您将一个值映射到另一个值。

因此您的代码可能看起来像这样。

List<string> unique_raw_filenames = AllAttributes.Where(x => x.ImageFileName.Contains(@"non")).Select(x => x.ImageFileName).ToList();

这会给你一个字符串列表。