如何通過除這些對象的屬性之外的其他屬性對對象列表進行分組?我需要將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