Linq Aggregate to generate string with nested classes
var outline = Grandparents.Select(
x =>
x.Parents.Select(
y =>
y.Children.Aggregate(string.Empty, (current, child) => string.Format("{0}{1},{2},{3},{4}\n",
current, x.Grandparent,
y.Parent,
child.Name,
child.Age))));
Grandparents is a class with two members:
string Grandparent
List<Parent> Parents
Parents is a class with two members:
string Parent
List<Child> Children
Child is a class with two members:
string Name
int Age
I want to use Linq to produce a string that I'll write to a开发者_开发知识库t text file, for example:
Grandpa Walter, Parent William, Child Chris, Age 11
Grandpa Walter, Parent Sue, Child Alice, Age 7
Grandpa Walter, Parent Sue, Child Sam, Age 7
Grandpa Eugene, Parent David, Child Joe, Age 17
The above code produces an IEnumearable of IEnumerable of String. I want to produce just a "string"
just flatten the sequence using SelectMany()
and use string.Join()
to aggregate:
string result = string.Join(Environment.NewLine, outline.SelectMany( x=>x));
Try this:
string result = (from grandParent in grandParents
from parent in grandParent.Parents
from child in parent.Children
select string.Format("{0}, {1}, {2}, {3}", grandParent.Name, parent.Name, child.Name, child.Age))
.Aggregate((a, b) => a + Environment.NewLine + b);
Anyway, instead of using Aggregate, I suggest you to save your text file using File.WriteAllLines
:
var results = from grandParent in grandParents
from parent in grandParent.Parents
from child in parent.Children
select string.Format("{0}, {1}, {2}, {3}", grandParent.Name, parent.Name, child.Name, child.Age)
File.WriteAllLines("myfile.txt", results);
The above query is going to return an IEnumerable<IEnumerable<string>>
, where each element represents a grandparent, and each of the strings within each element represent your aggregate for each parent.
While you could transform this into a second aggregate, this seems like using LINQ for the sake of using LINQ. You would be much better off using a StringBuilder
and just iterating over your collection. You'll produce code that is only slightly longer than your LINQ query, and it will be much easier to see what's actually going on.
Since your query doesn't define it, I'm not certain how you want to combine the results from each parent. If you can clarify that, I'll update this answer to reflect that.
精彩评论