[英]Generate string from Grouping Linq Query
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"? 是否可以用将输出包含以下两个字符串的IEnumerable
<string
>的select替换最后一行:“ Pendray John Richard”“ Emery Jake”? Is it possible to project a linq query into strings like this? 是否可以将linq查询投影成这样的字符串?
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) 编辑:我知道这可以通过进一步的代码实现,但是我对是否可以在linq查询本身中完成此操作感兴趣,这与VB能够从查询中投射xml的方式类似,例如http:// www。 thinqlinq.com/default/Projecting-XML-from-LINQ-to-SQL.aspx (尤其是此页面上的最后一个代码块)
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
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
最简单的方法是定义一个将使用IEnumerable并生成该字符串的函数,然后调用该函数
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.