这是我的第一个问题的编辑:所以我再次检查了作业。所有代码都按我的教授希望的那样工作,但只有我之前问过的问题才是我的问题。- 我如何直接从列表(当然)执行 ShowGrade 方法,例如:list[1].ShowGrade(0) 而不使用 list[1].s.ShowGrade(0) ?我会把我所有的代码放在这里。Main 中的两条控制台线是他想要的(以及他想要的方式),我对作业的限制是:1. 课程中的嵌套课程学生(课程一名学生)。2. 除了默认构造函数之外根本没有构造函数。3. ShowGrade 方法不会出现在 Course 类中。4.没有操作员。(点)在 ShowGrade 中,只有 [] 5. 在方法 Q1 中将只有一个查询。
所以我的代码是:
课程。CS:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HW_1
{
public class Course
{
private delegate int Del(Course c);
internal string courseName { get; set; }
public class Student
{
internal string stuName { get; set; }
internal List<int> gradesList { get; set; }
//internal int ShowGrade(int index)
//{
// return gradesList[index];
//}
}
internal Student s = new Student();
public override string ToString()
{
string gr = null;
foreach (var g in s.gradesList)
gr += g + " ";
return string.Format("{0, -6} {1, -14} {2, -10}", courseName, s.stuName, gr);
}
}
}
程序.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HW_1
{
class Program
{
private delegate bool Del(Course c);
static void Main(string[] args)
{
List<Course> list = new List<Course>
{
new Course {courseName = "C#", s = new Course.Student {stuName = "Jojo", gradesList = new List<int>(){10, 20, 100}}},
new Course {courseName = "C", s = new Course.Student {stuName = "Bambi", gradesList = new List<int>(){99}}},
new Course {courseName = "Java", s = new Course.Student {stuName = "Bambi", gradesList = new List<int>(){}}}
};
Console.WriteLine("List of courses:");
Print(list);
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("Press P / p for students who passed in average 60 and those who didn't.");
Console.WriteLine("");
Console.WriteLine("Press # for C# courses and others.");
Console.WriteLine("");
Console.WriteLine("Press any other key for courses with student who have at least one grade of 100 and all oter courses.");
char ch = (char)Console.Read();
Del d = ((ch == 'P' || ch == 'p') ? (Del)(c => c.s.gradesList.Count > 0 && c.s.gradesList.Average() >= 60) : ((ch == '#') ? (Del)(c => c.courseName == "C#") : (Del)(c => c.s.gradesList.Contains(100))));
var x = Q1 <IGrouping<bool, Course>>(list, d);
Print(x);
Console.WriteLine("");
//Console.WriteLine(list[1].ShowGrade(0));
//Console.WriteLine(list[2].ShowGrade(3));
}
static IEnumerable<T> Q1<T>(IEnumerable<Course> list, Del d)
{
var query =
from c in list
orderby d(c)
group c by d(c) into g
select g;
return (IEnumerable<T>)query;
}
static void Print(IEnumerable<IGrouping<bool, Course>> list)
{
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Q1 Results:");
foreach (var g in list)
{
Console.WriteLine();
Console.WriteLine(g.Key);
Console.WriteLine("---------------");
foreach (var c in g)
Console.WriteLine(c);
}
}
static void Print<T>(IEnumerable<T> list)
{
foreach (var l in list)
Console.WriteLine(l);
}
}
}
两个 Console.writeline 的输出必须是:
list[1].ShowGrade(0)
99
list[2].ShowGrade(3)