如何在对象初始化语法(foreach)中使用字符串拆分?

时间:2017-11-05 12:23:12

标签: c# foreach many-to-many

如何使用foreach循环来表示对象初始化程序语法?

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,

我想使用带有string.Split(new char [] {''}的foreach循环来表示我做的每个标记输入。

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

1 个答案:

答案 0 :(得分:1)

假设您在NewPostModel model上有一个属性,其中包含以空格分隔的一组标记,名称为SomeStringWithTags,您可以使用string.Split的结果作为选择投影的基础为每个字符串返回PostTag投影:

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`
 };

即。你根本不需要一个explcit foreach