LINQ名单判处格式(插入逗号和放大器;"和") [英] LINQ list to sentence format (insert commas & "and")
问题描述
我有一个LINQ查询,做一些简单的像:
I have a linq query that does something simple like:
var k = people.Select(x=>new{x.ID, x.Name});
然后我想,这将输出句子的格式名称使用逗号函数或LINQ拉姆达,或一些和阿富汗国家发展战略。
I then want a function or linq lambda, or something that will output the names in sentence format using commas and "ands".
{1, John}
{2, Mark}
{3, George}
到
"1:John, 2:Mark and 3:George"
我没事用硬编码 ID +:+姓名
的一部分,但它可能是依赖于LINQ查询结果的类型的ToString()。我只是想知道是否有一个整洁的方式与LINQ或的String.Format这样做()。
I'm fine with hardcoding the ID + ":" + Name
part, but it could be a ToString() depending on the type of the linq query result. I'm just wondering if there is a neat way to do this with linq or String.Format().
推荐答案
为什么LINQ的?
StringBuilder sb = new StringBuilder();
for(int i=0;i<k.Count();i++)
{
sb.Append(String.Format("{0}:{1}", k[i].ID, k[i].Name);
if(i + 2 < k.Count())
sb.Append(", ");
else if(i + 1 < k.Count())
sb.Append(" and ");
}
真的,所有的LINQ可以让你做的是隐藏循环。
Really, all Linq will let you do is hide the loop.
此外,还要确保你做或不想在牛津逗号,这种算法将不插入一个,而是一个小的变化会(追加逗号和除最后每个元素之后的空间,并且还追加和下一个到最后一个)。
Also, make sure you do or do not want the "Oxford Comma"; this algorithm will not insert one, but a small change will (append the comma and space after every element except the last, and also append "and " after the next-to-last).
这篇关于LINQ名单判处格式(插入逗号和放大器;"和")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!