LINQ-根据特定值排序对象列表

时间:2010-10-11 15:18:11

标签: c# linq-to-objects

我是LINQ的新手。我有一个这样的课:

public class StudentResults
{

    public int Id { get; set; }

    public ResultsStatus StatusResult { get; set; }

    public string Message { get; set; }

    public StudentDetails Detail { get; set; }

}

有一种方法可以将上述类的List返回给变量

我需要通过该变量进行迭代,并将学生分成两个不同的类。 PassedStudents,FailedStudents基于ResultsStatus。

这是我尝试过的但它不起作用

 var studIds = from r in StudList
 group r by r.Id into GroupedData
  select new 
  {
   //what to put here
  };
  foreach(var crs in studIds)
  {
   //what to put here to get all student names from the Detail property.
  }

还有其他办法吗?

3 个答案:

答案 0 :(得分:3)

就个人而言,我只想将其视为两个问题:

var passed = StudList.Where(student => student.StatusResult == ResultStatus.Passed);
var failed = StudList.Where(student => student.StatusResult == ResultStatus.Failed);

Console.WriteLine("Passed...");
foreach(var student in passed)
   Console.WriteLine(student.Detail.Name);

Console.WriteLine("Failed...");
foreach(var student in failed)
   Console.WriteLine(student.Detail.Name);

答案 1 :(得分:2)

听起来你喜欢2个列表:一个用于失败,一个用于传递。

试试这个:

List<StudentResults> failed = StudList.Where(x=>x.ResultStatus=="Failed")
                                      .ToList();

List<StudentResults> passed = StudList.Where(x=>x.ResultStatus=="Passed")
                                      .ToList();

答案 2 :(得分:1)

只需使用“where”。例如,要获得所有“PassedStudents”:

var passedStudents = from student in StudentList
                     where student.StatusResult == ResultsStatus.PassedStudent
                     select student;

foreach (var student in passedStudents)
{
    Console.WriteLine("[{0}.] {1} passed.", student.Id, student.Detail.Name);
}

您也可以使用lambda表达式编写查询:

var passedStudents = 
    StudentList.Where(student => student.StatusResult == ResultsStatus.PassedStudent);