我注意到在编写LINQ-y代码时,.ForEach()是一个很好用的习惯用法.例如,这是一段代码,它接受以下输入,并产生这些输出:
{ "One" } => "One"
{ "One", "Two" } => "One, Two"
{ "One", "Two", "Three", "Four" } => "One, Two, Three and Four";
Run Code Online (Sandbox Code Playgroud)
和代码:
private string InsertCommasAttempt(IEnumerable<string> words)
{
List<string> wordList = words.ToList();
StringBuilder sb = new StringBuilder();
var wordsAndSeparators = wordList.Select((string word, int pos) =>
{
if (pos == 0) return new { Word = word, Leading = string.Empty };
if (pos == wordList.Count - 1) return new { Word = word, Leading = " …Run Code Online (Sandbox Code Playgroud)