S
shapper
Hello,
I have a List<Subject> Subjects where each subject has an Id and a
Name.
I want to create a String from that list as follows:
"Subject1, Subject2 and Subject3" or "Subject1" if only one exists.
I tried the following
:
String subjects = String.Join(", ", source.Select(s =>
s.Name).ToArray());
Int32 index = subjects.LastIndexOf(",");
subjects.Remove(index).Insert(index, " and ");
return subjects;
The "and" is being added but the last subject removed. What is the
correct way to do this?
And if there is only one subject I get an error ...
.... Well I think I can solve this by using:
if (source.Count == 1)
return source.FirstOrDefault().Name.ToString();
I am not sure if this is the best way ...
In fact, source can be empty or null ...
Thanks,
Miguel
I have a List<Subject> Subjects where each subject has an Id and a
Name.
I want to create a String from that list as follows:
"Subject1, Subject2 and Subject3" or "Subject1" if only one exists.
I tried the following
:
String subjects = String.Join(", ", source.Select(s =>
s.Name).ToArray());
Int32 index = subjects.LastIndexOf(",");
subjects.Remove(index).Insert(index, " and ");
return subjects;
The "and" is being added but the last subject removed. What is the
correct way to do this?
And if there is only one subject I get an error ...
.... Well I think I can solve this by using:
if (source.Count == 1)
return source.FirstOrDefault().Name.ToString();
I am not sure if this is the best way ...
In fact, source can be empty or null ...
Thanks,
Miguel