开发者

LINQ- Ordering a list of objects based on a particular value

I am new to LINQ. I have a class like this:

开发者_开发百科public class StudentResults
{

    public int Id { get; set; }

    public ResultsStatus StatusResult { get; set; }

    public string Message { get; set; }

    public StudentDetails Detail { get; set; }

}

There is a method that returns a List of the above class to a variable

I need to iterate thru that variable and put the students into two different classes. PassedStudents, FailedStudents based on ResultsStatus.

Here is what I have tried but it doesnt work

 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.
  }

Is there another way?


Personally, I would just treat this as two queries:

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);


Sounds like you'd like 2 lists: one for failed, and one for passed.

Try this:

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

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


Simply use "where". For instance, to get all the "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);
}

You can also write the query using lambda expressions:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜