I have a simple text file containing some CSV with the following structure:
@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.
'@' indicates the parent of the child objects that is below it. (This could be better represented using XML, but this is not an option in my case.)
My goal is to use LINQ to query this file without loading all its contents into memory. First, I created a class (here: MyCustomReader) that implements IEnumerable, in which I use StreamReader to get each line of the file.
eg. The following gets all the parent objects (without children):
from line in MyCustomReader
where line.StartsWith("@")
select Parent.Create(line)
, , , , . , , .
. :
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.Create(line);
if (child.FiledValue == childFiledValue)
yield return parent;
}
}
}
LINQ?