【发布时间】:2010-11-20 09:33:31
【问题描述】:
我有一个简单的文本文件,其中包含一些具有以下结构的 CSV:
@Parent1_Field1, Parent1_Field2, Parent1_Field3 Child1_Field1, Child1_Field2 Child2_Field1, Child2_Field2 ...etc. @Parent2_Field1, Parent2_Field2, Parent2_Field3 Child1_Field1, Child1_Field2 Child2_Field1, Child2_Field2 ...etc.
'@' 表示紧接其下的子对象的父对象。 (这可以使用 XML 更好地表示,但在我的情况下这不是一个选项。)
我的目的是使用 LINQ 查询此文件,而不会将其全部内容加载到内存中。首先,我创建了一个实现 IEnumerable 的类(此处为 MyCustomReader),在该类中我使用 StreamReader 来获取文件的每一行。
例如以下获取所有 Parent 对象(不包括子对象):
from line in MyCustomReader
where line.StartsWith("@")
select Parent.Create(line)
但是,当我想创建涉及 Parent 和 Child 对象的查询时,我遇到了困难。例如,获取特定父对象的所有子对象或获取特定子字段包含相同值的所有父对象。
例如这将获取特定 Parent 对象的所有子对象:
public IEnumerable<Child> GetChildrenForAParent(string uniqueParentName)
{
Parent parent = null;
foreach (string line in MyCustomReader)
{
if (line.StartsWith("@"))
parent = Parent.Create(line);
else if (parent.UniqueName == uniqueParentName)
yield return Child.Create(line);
}
}
第二个例子:
public IEnumerable<Parent> GetParentsWhereChildHasThisValue(string childFiledValue)
{
Parent parent = null;
foreach (string line in MyCustomReader)
{
if (line.StartsWith("@"))
{
parent = Line.Create(line);
}
else //child
{
Child child = Child.Create(line);
if (child.FiledValue == childFiledValue)
yield return parent;
}
}
}
如何使用 LINQ 实现这两个示例?
【问题讨论】:
标签: c# linq csv text-files