【发布时间】:2019-12-09 10:52:37
【问题描述】:
我正在尝试使用“包含”方法提取与子字符串匹配的文件名。然而,回报似乎是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();
}
}
}
数据类型类
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() 不起作用? (它返回 List<char> 但我期待 List<string> 并且失败了。
【问题讨论】:
-
你为什么期望
x.ToList(),其中x是String,产生List<String>? -
FirstOrDefault应用于Where查询的结果,这可能是一个可枚举的。因此,您只采用 first 对象的ImageFileName(可能是一个字符串),然后转换该字符串ToList将创建其字符列表。 -
归结为您将 ToList() 应用于错误的事物。你把它应用到一个字符串上,而不是......无论你当时期望的东西是什么。属性名称是赠品 -
ImageFileName听起来像是一个文件名,而不是文件名的集合。string而不是List<string>或string[]或您在这里期望的任何其他内容。