Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ list to sentence format (insert commas & "and")

Tags:

string

c#

linq

I have a linq query that does something simple like:

var k = people.Select(x=>new{x.ID, x.Name});

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}

to

"1:John, 2:Mark and 3:George"

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().

like image 353
Harry Avatar asked Sep 29 '10 17:09

Harry


2 Answers

public string ToPrettyCommas<T>(
  List<T> source,
  Func<T, string> stringSelector
)
{
  int count = source.Count;

  Func<int, string> prefixSelector = x => 
    x == 0 ? "" :
    x == count - 1 ? " and " :
    ", ";

  StringBuilder sb = new StringBuilder();

  for(int i = 0; i < count; i++)
  {
    sb.Append(prefixSelector(i));
    sb.Append(stringSelector(source[i]));
  }

  string result = sb.ToString();
  return result;
}

Called with:

string result = ToPrettyCommas(people, p => p.ID.ToString() + ":" + p.Name);
like image 153
Amy B Avatar answered Oct 05 '22 11:10

Amy B


Why 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 ");
}

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

like image 45
KeithS Avatar answered Oct 05 '22 11:10

KeithS