2

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)

2 Answers 2

4
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

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.