//存放数据的集合
var topicList = db.Topics.ToList();
//要转存的集合
List<getTopic> lgt = new List<getTopic>();
//遍历存放数据集合的数据
foreach (var item in topicList)
{
//要转存的对象(模型类)
getTopic gt = new getTopic();
//对象中的属性对应
gt.TID = item.TopicId;
gt.TExplain = item.TopicExplain;
gt.TScore = item.TopicScore;
gt.TType = item.TopicType;
gt.TAnswer = item.TopicAnswer;
gt.TpaperId = item.PaperId;
gt.TSort = item.TopicSort;
List<TopicSelect> selects = new List<TopicSelect>();
selects.Add(new TopicSelect { Tselect = "A", topics = item.TopicA });
selects.Add(new TopicSelect { Tselect = "B", topics = item.TopicB });
selects.Add(new TopicSelect { Tselect = "C", topics = item.TopicC });
selects.Add(new TopicSelect { Tselect = "D", topics = item.TopicD });
gt.topicSelect = selects;
//将数据添加进要转存的集合中
lgt.Add(gt);
}
对应的模型类
public class TopicSelect
{
/// <summary>
/// 选项标识
/// </summary>
public string? Tselect { get; set; }
/// <summary>
/// 选型内容
/// </summary>
public string? topics { get; set; }
}
public class getTopic
{
/// <summary>
/// ID
/// </summary>
public int TID { get; set; }
/// <summary>
/// 描述
/// </summary>
public string? TExplain { get; set; }
/// <summary>
/// 分数
/// </summary>
public int? TScore { get; set; }
/// <summary>
/// 类型
/// </summary>
public int? TType { get; set; }
/// <summary>
/// 排序
/// </summary>
public int? TSort { get; set; }
/// <summary>
/// 答案
/// </summary>
public string? TAnswer { get; set; }
/// <summary>
/// 试卷ID
/// </summary>
public int? TpaperId { get; set; }
/// <summary>
///选项
/// </summary>
public List<TopicSelect>? topicSelect { get; set; }
}
优化一下
var topicList = db.Topics.ToList();
List<getTopic> lgt = topicList.Select(item => new getTopic
{
TID = item.TopicId,
TExplain = item.TopicExplain,
TScore = item.TopicScore,
TType = item.TopicType,
TAnswer = item.TopicAnswer,
TSort = item.TopicSort,
TpaperId = item.PaperId,
topicSelect = new List<TopicSelect>
{
new TopicSelect { Tselect = "A", topics = item.TopicA },
new TopicSelect { Tselect = "B", topics = item.TopicB },
new TopicSelect { Tselect = "C", topics = item.TopicC },
new TopicSelect { Tselect = "D", topics = item.TopicD }
}
}).ToList();