Alan2
Alan2

Reputation: 24572

How can I extract data from each line contained in a string and put this into a collection in C#

I have some a collection of data inside a tuple:

IEnumerable<Tuple<string, string>>

My Topic and SubTopic classes looks like this:

public partial class Topic
{
    public Topic()
    {
        this.SubTopics = new List<SubTopic>();
    }
    public string Name { get; set; }
    public virtual ICollection<SubTopic> SubTopics { get; set; }
}

public partial class SubTopic
{
    public string Name { get; set; } 
}

I am using Entity Framework and so far my code to return a list of Topics looks like this:

public IList<Topic> createTopics(string subjectName)
{
    IEnumerable<Tuple<string, string>> topicData = GetContent.GetType6();
    var topics = topicData.Select((o, index) => new Topic
    {
        Name = o.Item1,
        SubTopics = ??
    }
    );
    return topics.ToList(); 
}

Can someone tell my how I can get the SubTopic names out of Item2 and put them into SubTopics which is into the SubTopics field which is an ICollection

Upvotes: 0

Views: 91

Answers (2)

Matthew Watson
Matthew Watson

Reputation: 109742

I think this should work for your SubTopics = ??

SubTopics = o.Item2.Split(new [] {'\n'} )
            .Select(x => new SubTopic { Name = x })
            .ToList();

Upvotes: 2

Bob Vale
Bob Vale

Reputation: 18474

public IList<Topic> createTopics(string subjectName)
{
    var topics = from o in GetContent.GetType6()
                 select new Topic
                 {
                    Name = o.Item1,
                    SubTopics = o.Item2.Split('\n')
                                       .Select(x => new SubTopic { Name = x})
                                       .ToArray();
                 };
     return topics.ToList();
}

Upvotes: 0

Related Questions