Reputation: 222
Given the following code:
var people = new List<person>(){ new person { Name = "John", FamilyName = "Pendray" },
new person { FamilyName = "Emery", Name = "Jake"},
new person { FamilyName = "Pendray", Name = "Richard" } };
var q = from p in people
orderby p.Name
group p by p.FamilyName into fam
orderby fam.Key
select new { fam.Key, members = from p in fam select p };
Is it possible to replace the last line with a select that will output a IEnumerable<string
> that contains these two strings:
"Pendray John Richard"
"Emery Jake"? Is it possible to project a linq query into strings like this?
Edit: I know this is possible with further code but I'm interested in whether this can be done from within the linq query itself in a similar way to VB being able to project xml out of a query as in http://www.thinqlinq.com/default/Projecting-XML-from-LINQ-to-SQL.aspx (particularly the last code block on this page)
Upvotes: 2
Views: 954
Reputation: 71856
var q = from p in people
orderby p.Name
group p by p.FamilyName into fam
orderby fam.Key
select fam.Key + " " + string.Join(" ", (from fm in fam select fm.Name).ToArray());
Returns
Emery Jake
Pendray John Richard
Upvotes: 4
Reputation: 41616
Definitely.
You would have to change the select part. The easiest way would be to define a function that would take the IEnumerable and generate that string, then call that function
people = new List<person>(){ new person { Name = "John", FamilyName = "Pendray" },
new person { FamilyName = "Emery", Name = "Jake"},
new person { FamilyName = "Pendray", Name = "Richard" } };
var q = from p in people
orderby p.Name
group p by p.FamilyName into fam
orderby fam.Key
select new { Key = fam.Key, Text = GetText(fam) };
// and elsewhere...
private string GetText(IEnumerable<person> family) {
string result = "Whatever"; // build the result string here
return result;
}
Also, if you only want the text, you can change the last line of the query to simply
select GetText(fam);
Upvotes: 0