1

Is it possible in C# to combine the Name properties of the List<Tag> object with a comma "," with a line command? "World,Tech,Science,Arts"

public class Tag
{
   public int Id { get; set; }
   public string Name { get; set; }
}
List<string> tagNames;
foreach (var tag in tags)
{
   tagNames.add(tag.Name);
}
string result = String.Join(",", tagNames);

I tried this but it doesn't work

string result = String.Join(",", tags.ForEach(t => t.Name));
2
  • 1
    You should use Select, not ForEach and make sure you have using System.Linq; Commented Dec 26, 2020 at 20:31
  • 1
    List's ForEach has done more damage for people's understanding of LINQ, than good for C# as a whole Commented Dec 26, 2020 at 20:40

2 Answers 2

3

ForEach runs a block of code. You're looking for Select that projects each element in a different form:

string result = String.Join(",", tags.Select(t => t.Name));
Sign up to request clarification or add additional context in comments.

Comments

2

Is it possible in C# to combine the Name properties of the List object with a comma "," with a line command?

Another one-liner using Aggregate instead of String.Join():

string result = tags.Select(t => t.Name).Aggregate((a, b) => (a + "," + b));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.