如何通过除这些对象的属性之外的其他属性对对象列表进行分组?我需要将List统计分组。列表中的每个对象都有属性字符串Question,并且对于每个Question都有一些可能的答案,我希望将列表分组(每个组具有相同的可能答案),但这些可能的答案与Statistics类没有直接关系。通过除这些对象的属性之外的其他属性对对象列表进行分组
我想要做这样的事情:
var customGroups = from stat in statistics group stat by new { PossibleAnswers = questions.SingleOrDefault(q => q.Text == stat.Question).PossibleAnswers };
foreach (var group in customGroups)
{
StatisticsWithSamePossibleAnswers.Add(group.ToList());
}
的代码提供运行时异常:对象引用不设置到对象的实例。
那么这样做的好方法是什么?我知道我总是可以使用嵌套的foreach循环,但是有什么更明智的吗?
类统计和问题是这样的:
public class Statistics
{
public int ID { get; set; }
public int Year { get; set; }
public int Semester { get; set; }
public string Subject { get; set; }
public string Question { get; set; }
public bool IsAssociatedWithProfessor { get; set; }
public bool IsAssociatedWithAssistant { get; set; }
public string Answer { get; set; }
public int NumberOfAnswers { get; set; }
public double AnswerPercentage { get; set; }
public double? AM { get; set; }
public double? SD { get; set; }
}
public class Question
{
public int ID { get; set; }
public string Text { get; set; }
public bool IsAssociatedWithProfessor { get; set; }
public bool IsAssociatedWithAssistant { get; set; }
public virtual ICollection<PossibleAnswer> PossibleAnswers { get; set; }
public virtual ICollection<Results> Results { get; set; }
}
你能提供一个像结构的小样本吗?我只是想确定我的理解正确 – CheGueVerra 2015-02-06 23:56:57
目前,你的代码正在抛出,因为'questions'中没有匹配的元素。但我正在为一般情况寻找答案。 – recursive 2015-02-07 00:20:57
我用一个Where替换了SingleOrDefault,并在最后注释了这部分.PossibleAnswers,似乎正在工作,但SingleOrDefault我不明白为什么你正在使用它 – CheGueVerra 2015-02-07 00:26:14