Search code examples
c#foreachmany-to-many

How do I use a string split in object initialiser syntax (foreach)?


How can I use a foreach loop to represent the object initializer syntax?

public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public ICollection<PostTag> PostTags { get; set; }
}

public class PostTag
{
public int TagId { get; set; }
public Tag Tag { get; set; }
public int PostId { get; set; }
public Post Post { get; set;}
}

public class Tag
{
public int TagId { get; set; }
public string Name { get; set; }
public ICollection<PostTag> PostTags { get; set }
}

public IActionResult Add(NewPostModel model)
{
    return new Post()
    {
        Title = model.Title,

        Content = model.Content,

I would like to use a foreach loop with a string.Split(new char[]{ ' ' } to represent each tag input I do.

 PostTags = new List<PostTag> ()
        {
            new PostTag ()
            {
                Tag = new Tag (){ Name = Name};
            }
        }
    }
}

Solution

  • Assuming you have a property on NewPostModel model with a space delimited set of tags, with the name SomeStringWithTags, you can use the result of the string.Split as a basis for a Select projection to return a PostTag projection for each string:

    return new Post
    {
        Title = model.Title,
        Content = model.Content,
        PostTags = model.SomeStringWithTags.Split(new []{' '})
              .Select(s => 
              {
                 new PostTag
                 {
                     Tag = new Tag { Name = s }
                 }
              }
              .ToList() // .. needed because of the `ICollection`
     };
    

    i.e. You won't actually need an explcit foreach at all.