现有结构(由于系统要求无法更改)
class Statement
{
string section;
string category;
string statement;
}
示例语句列表
section category statement
1 a apple
1 a banana
1 b potato
2 c car
2 c bus
2 d plane
问题
我有一个 List<Statement>
,需要根据章节和类别进行拆分,并将其转换为以下(或类似)结构:
struct SectionCollection
{
string sectionName {get{return categories[0].section;}}
List<CategoryCollection> categories;
}
struct CategoryCollection
{
string categoryName {get{return statements[0].category;}}
List<Statement> statements;
}
因此,从
List<Statement>
中,我应该有一个List<SectionCollection>
,其中包含一个List<CategoryCollection>
,其中包含一个List<Statement>
。因此,在上面的数据示例中,我将拥有
List<SectionCollection>
List<CategoryCollection>
(内部)List<Statement>
(内部)
SectionCollection
s
尝试
我的当前尝试,它可以正常工作,直到最终在内部循环中抛出空异常。这是我一直在研究的问题之一,所以我知道这个“解决方案”可能看起来很困惑。var sections = statements.GroupBy(x => x.section).Select(y => y.ToList()).ToList();
foreach(var section in sections)
{
SectionCollection thisSection = new SectionCollection();
var categories = section.GroupBy(x => x.category).Select(y => y.ToList()).ToList();
foreach(var category in categories)
{
thisSection.categories.Add(new CategoryCollection({statements = category});
}
}
thisSection.categories
被初始化为new
。 - MFisherKDX