0

我有数据放入这样的列表中:

var data = new List<string>();
            data.Add("topic1 - subtopic1");
            data.Add("topic1 - subtopic2");
            data.Add("topic1 - subtopic3");
            data.Add("topic2 - subtopic4");
            data.Add("topic3 - subtopic5");

我有两节课:

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

public partial class SubTopic {
   public int SubTopicId { get; set; }
   public int Number { get; set; }
   public string Name { get; set; }
   public int TopicId { get; set; }
   public virtual Topic Topic { get; set; }
}

有没有一种简单的方法可以遍历列表中的每条记录,并将“-”左侧的文本插入主题,将“-”右侧的文本插入子主题?对我来说,问题是如何处理父子关系,以便使用这些数据最终得到一个只有三个记录的 Topic 对象。

4

3 回答 3

3

您还可以使用 LINQ:

var separator = new[] { "-" };
var topics = data.Select(s => s.Split(separator, StringSplitOptions.RemoveEmptyEntries))
    .GroupBy(strings => strings[0])
    .Select(grouping => new Topic
    {
        Name = grouping.Key,
        SubTopics = grouping.Select(s => new SubTopic {Name = s[1]}).ToList()
    })
    .ToArray();
于 2013-08-01T03:21:50.477 回答
1

你必须使用字典。像这样的东西,

Dictionary<string,Topic> topics = new Dictionary<string,Topic>();
foreach(string topic in data)
{
string[] values = topic.split(new string[]{"-"});
if( !topic.ContainsKey(values[0]) )
  topic.Add(values[0], new Topic());
Topic topic = topics [values[0];
topic.Name = values[0];
topic.SubTopics.Add( new SubTopic(){Name = values[1]};
}
于 2013-08-01T03:20:19.840 回答
1
var data = new List<string>();
data.Add("topic1 - subtopic1");
data.Add("topic1 - subtopic2");
data.Add("topic1 - subtopic3");
data.Add("topic2 - subtopic4");
data.Add("topic3 - subtopic5");

var memo = new Dictionary<string, Topic>();

foreach (var parts in data.Select(item => item.Split('-').Select(x=>x.Trim()).ToArray()))
{
    if (!memo.ContainsKey(parts[0]))
    {
        memo.Add(parts[0], new Topic {Name = parts[0]});
    }
    memo[parts[0]].SubTopics.Add(new SubTopic { Name = parts[1], Topic = memo[parts[0]] });
}

var result = memo.Values.ToList();
于 2013-08-01T03:28:46.630 回答