【发布时间】:2018-08-01 16:50:25
【问题描述】:
当前结构(因系统要求无法更改)
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>开头,需要根据Section将它们拆分,然后分类成如下(或类似)结构
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>(内)
-
-
备注
一个语句或一个类别在不同的部分可能相同并非不可能——它们仍然需要属于不同的SectionCollections
尝试
我当前的尝试,直到最终在内部 for 循环中引发空异常为止。这是我一直在关注的问题之一,所以我知道这个“解决方案”看起来有多混乱。
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 这可能只是问题所在。我现在正在研究这个问题,但我觉得我已经尝试过了,只是(愚蠢地)把它从我的例子中删除了已经提供了
标签: c# list data-structures struct