How to get the sum of integers in multiple objects? - c#

I have two objects they are: Student and Courses:
public Student(string StudentID, string Name, string Status, Enum StudentMajor, Dictionary<Courses, Grade[]> CompletedCourses)
public Courses(string courseName, string courseCode, string passingGrade, int numOfCredits, List<Courses> prerequisites)
Here's the objects I created in my Main class
//Courses
Courses ITEC_120 = new("Introduction to Computer Hardware", "ITEC 120", "C", 3, new List<Courses> {});
Courses ITEC_122 = new("Introduction to Operating Systems", "ITEC 122", "C", 3, new List<Courses> { ITEC_120 });
//Student
Student student1 = new("00069110", "Antony Dos Santos", "Full-time", Majors.Computer_Information_Systems, new Dictionary<Courses, Grade[]>()
{
{ ITEC_120, new[] { Grade.F, Grade.B, Grade.Not_Taken } },
{ ITEC_122, new[] { Grade.A, Grade.Not_Taken, Grade.Not_Taken }
},
});
As you can see the courses have a variable called credit and each Student object has a dictionary that takes a Course and a Grade
So student1 has two courses and each of the courses has 3 credits each. How would I iterate over the Dictionary to get the total of all the courses in CoursesCompleted in this case it should be 6.
Each object is added to a List
//List for Courses objects
List<Courses> CompulsoryCourses = new List<Courses>();
CompulsoryCourses.Add(ITEC_120);
CompulsoryCourses.Add(ITEC_122);//Adding the two courses to the List
List for Student objects
List<Student> students = new List<Student>();
students.Add(student1);
foreach(var stu in students)
{
var GPA = 0.0;
var CourseCredits = 0;
Console.WriteLine("\nStudent Information");
foreach (KeyValuePair<Courses, Grade[]> item in stu.CompletedCourses)
{
var TotalCredits = CourseCredits+item.Key.numOfCredits;
Console.WriteLine("\nName: " + item.Key.courseName + ", Credits: " + item.Key.numOfCredits);
GPA = stu.calGPA(CourseCredits);
Console.WriteLine("Total Credits: "+TotalCredits);
}
Console.WriteLine(stu.Name+ ": GPA = " + GPA);
}
In the foreach loop above I'm looping through the students List, and then I use another foreach loop to iterate the Dictionary to get the Key which in this case is numOfCredits like: item.Key.numOfCredits, and add them to each other.
Currently it's only adding the numOfCredits to itself and not to the other course in the dictionary.

You can use LINQ for something like this. If you have a list of cars and want to sum just the price you can do this:
var cars = new List<Car>
{
new Car{ BrandName = "Lamborghini", Model = "Huracan", Price = 300000M },
new Car{ BrandName = "Porsche", Model = "Gt3rs", Price = 200000M },
new Car{ BrandName = "Vauxhall", Model = "Corsa", Price = 20000M }
};
var totalPrice = cars.Sum(car => car.Price);
Console.WriteLine($"Total Price: {totalPrice}");
Where 'Car' looks like this:
public class Car
{
public string BrandName { get; set; }
public string Model { get; set; }
public decimal Price { get; set; }
}

Not sure exactly what you are asking for. But adding the sum of the cars "prices" i assume.
You could create a list, where all cars are added, along with all new cars.
Then what you could do it creating a for loop, thats the lengt of that spesific list. And through that loop add all values. Would look something like this:
Class creation
class Car
{
public string name;
public int price;
public Car(string name, int price)
{
this.name = name;
this.price = price;
}
}
Then for creating the list, and adding some cars.
Car car1 = new Car("blue-car", 15);
Car car2 = new Car("red-car", 15);
List<Car> cars = new List<Car>() { car1, car2 };
And then finnaly we count the sum up.
int totalprice = 0;
for (int i = 0; i < cars.Count; i++)
{
totalprice = totalprice + cars[i].price;
}

Output
If have only Student and Course classes (for simplification) and want this
Name: Andy
Credits: 4
GPA: 2.25
Course Credits Grade P/F
ITEC 100 1 C Fail
ITEC 100 1 B Pass
ITEC 122 3 C Pass
Name: Jill
Credits: 4
GPA: 3.75
Course Credits Grade P/F
ITEC 100 1 B Pass
ITEC 120 3 A Pass
Name: Peter
Credits: 4
GPA: 2.5
Course Credits Grade P/F
ITEC 100 1 A Pass
ITEC 122 3 C Pass
Name: Rosy
Credits: 4
GPA: 2.25
Course Credits Grade P/F
ITEC 100 1 B Pass
ITEC 122 3 F Fail
ITEC 122 3 D Fail
ITEC 122 3 C Pass
but with the additional logic of tracking passing and/or falling classes, and restrictions on re-enrolling into classes etc, then look at the example below:
Program
The test program below defines 3 classes and 5 students. Then enrolls students to classes and assigns grades. Finally it loops through each student and each class the student has taken to enumerate their grades, and also calculate GPA
static class Program
{
static void Main(string[] args)
{
var courses = new List<Course>
{
new Course("ITEC 100", "Introduction to Project Managment", 1, Grade.B),
new Course("ITEC 122", "Introduction to Operating Systems", 3, Grade.C),
new Course("ITEC 120", "Introduction to Computer Hardware", 3, Grade.D),
};
var students = new List<Student>
{
new Student("Andy"),
new Student("Jill"),
new Student("Peter"),
new Student("Rosy"),
};
students[0].EnrolledInClass(courses[0], Grade.C); // fail
students[0].EnrolledInClass(courses[0], Grade.B); // pass
students[0].EnrolledInClass(courses[1], Grade.C); // pass
students[1].EnrolledInClass(courses[0], Grade.B);
students[1].EnrolledInClass(courses[2], Grade.A);
students[2].EnrolledInClass(courses[0], Grade.A);
students[2].EnrolledInClass(courses[1], Grade.C);
students[3].EnrolledInClass(courses[0], Grade.B);
students[3].EnrolledInClass(courses[1], Grade.F); // fail
students[3].EnrolledInClass(courses[1], Grade.D); // fail
students[3].EnrolledInClass(courses[1], Grade.C); // fail
foreach (var student in students)
{
Console.WriteLine($"Name: {student.Name}");
Console.WriteLine($"Credits: {student.TotalCredits}");
Console.WriteLine($"GPA: {student.GPA}");
Console.WriteLine($" {"Course", -9} {"Credits",-8} {"Grade",-5} {"P/F",-5}");
foreach ((Course course, Grade grade) in student.Courses)
{
string pass = course.IsPassing(grade) ? "Pass" : "Fail";
Console.WriteLine($" {course.Code, -9} {course.Credits,-8} {grade,-5} {pass,-5}");
}
Console.WriteLine();
}
}
}
Logic
Most of the logic is in the Courses class where a particular grade is checked to see if it passes, it calculates the rewarded credit hours and the awarded credit-grades.
The data is stored in a private List<(Course,Grade)> per student, and methods exist to check if you can enroll and to enroll students as well as calculate credit hours and GPA.
public enum Grade
{
F = 0,
D,
C,
B,
A,
}
public class Student
{
private readonly List<(Course course, Grade grade)> _courses;
public Student(string name)
{
Name = name;
_courses = new List<(Course, Grade)>();
}
public string Name { get; }
public IReadOnlyList<(Course course, Grade grade)> Courses => _courses;
public int FirstIndexOf(Course course)
{
for (int i = 0; i < Courses.Count; i++)
{
var item = Courses[i];
if (item.course == course)
{
return i;
}
}
return -1;
}
public int LastIndexOf(Course course)
{
for (int i = Courses.Count - 1; i >= 0; i--)
{
var item = Courses[i];
if (item.course == course)
{
return i;
}
}
return -1;
}
public bool HasTakenCourse(Course course)
{
return FirstIndexOf(course) >= 0;
}
public bool HasPassedCourse(Course course)
{
int index = LastIndexOf(course);
if (index >= 0)
{
var item = Courses[index];
return course.IsPassing(item.grade);
}
return false;
}
public bool CanEnrollInCourse(Course course)
{
int takenCount = 0;
for (int i = 0; i < Courses.Count; i++)
{
var item = Courses[i];
if (item.course == course)
{
if (course.IsPassing(item.grade))
{
// Cannot enroll twice in same class with passing grade
return false;
}
takenCount++;
if (takenCount > 3)
{
// Cannot enroll in class > 3 times
return false;
}
}
}
return true;
}
public bool EnrolledInClass(Course course, Grade grade)
{
if (CanEnrollInCourse(course))
{
_courses.Add((course, grade));
return true;
}
return false;
}
public int TotalCredits
{
get
{
return Courses.Sum((item) => item.course.GetCredits(item.grade));
}
}
public float GPA
{
get
{
float creditGrades = Courses.Sum((item) => item.course.GetCreditGrade(item.grade));
return creditGrades / TotalCredits;
}
}
}
public class Course
{
public Course(string code, string description, int credits, Grade passingGrade = Grade.D)
{
Code = code;
Description = description;
Credits = credits;
PassingGrade = passingGrade;
}
public string Code { get; }
public string Description { get; }
public int Credits { get; }
public Grade PassingGrade { get; }
public bool IsPassing(Grade grade) => grade >= PassingGrade; // check if grade is passing
public int GetCredits(Grade grade) => IsPassing(grade) ? Credits : 0; // only credit passing grades
public float GetCreditGrade(Grade grade) => GetCredits(grade) * (int)grade; // combine credit hours with grades, or zero for fail
}

Related

How to Read This Text File and store in a list using C#

The Text File Data is Like Below:
S.No Name Description Quantity Rate Discount Amount
1 Apple Friut is 12 24.02 0 242
Good for
health
2 Orange Friut 5 12.22 3 128
3 Banana Friut 5 12.22 3 128
4 Grapes Friut 5 12.22 3 128
I want to add all the Rows& Columns in list but Description column have multiple Rows in single item. How can I Solve this. I add My Existing Code Here:
My Existing Code is as follows:
class Program
{
static void Main(string[] args)
{
var dd = File.ReadAllLines(
"C:\\Users\\Trainee\\Desktop\\Saravanan_Test\\27.8.2018\\Inputfile.txt")
.Skip(1)
.Where(s => s.Length > 1)
.Select(x => splits(x)).ToList();
foreach (var item in dd)
{
Console.WriteLine(item.id+"\t"
+ item.Name+"\t"
+ item.Description+"\t"
+ item.Quantity+"\t"
+ item.Rate+"\t"
+ item.Discount+"\t"
+ item.Amount);
}
Console.ReadKey();
}
private static Class1 splits(string x)
{
var columns = x.Split('\t').Where(c => c != "").ToList();
return new Class1
{
id = Convert.ToInt32(columns[0]),
Name = columns[1],
Description = columns[2],
Quantity = Convert.ToInt32(columns[3]),
Rate = Convert.ToDouble(columns[4]),
Discount = Convert.ToInt32(columns[5]),
Amount = int.Parse(columns[6])
};
}
}
class Class1
{
public int id { get; set; }
public string Name { get; set; }
public String Description { get; set; }
public int Quantity { get; set; }
public double Rate { get; set; }
public int Discount { get; set; }
public int Amount { get; set; }
}
I want to store data into list like:
list.Add(new{ sno=1, Name="Apple",
Description="Friut is good for Health",
Quantity=12, Rate=24.02, Discount=0,
Amount=242 });
Thanks in Advance.
NOTE: This solution is based on the file shared in question. Data is separated by spaces and format is not advisable to use. Answering to help person with content format he has. Tested and working.
static void Main(string[] args)
{
List<Data> list = new List<Data>();
var dd = File.ReadAllLines(#"C:\Users\XXXX\Desktop\test.txt")
.Skip(1)
.Where(s => s.Length > 1).ToList();
foreach (var item in dd)
{
var columns = item.Split('\t').Where(c => c.Trim() != string.Empty).ToList();
if (columns != null && columns.Count > 0)
{
int id;
if (int.TryParse(columns[0], out id))
{
list.Add(new Data()
{
id = Convert.ToInt32(columns[0]),
Name = columns[1],
Description = columns[2],
Quantity = Convert.ToInt32(columns[3]),
Rate = Convert.ToDouble(columns[4]),
Discount = Convert.ToInt32(columns[5]),
Amount = int.Parse(columns[6])
});
}
else
{
list.Last().Description += columns[0];
}
}
}
Console.ReadLine();
}

C# Assigning to strings from a public class and list

so far my code does the following.
Ask user for a numeric amount for 'players'
Then asks for names for each of the players which is added to a list and class
I'd like to call those names from the list or class (not really sure how class works) and assign it to a new string. Here's what I got so far:
public class NameVariable
{
public int ID { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
bool IsUserWrong = false;
Console.WriteLine("Write amount of players");
while (!IsUserWrong)
{
int TotalPlayers;
while (!Int32.TryParse(Console.ReadLine(), out TotalPlayers))
{
Console.WriteLine("Value must be numeric.");
}
if (TotalPlayers >= 12 && TotalPlayers <= 16)
{
List<NameVariable> PlayerList = new List<NameVariable>();
for (int index = 0; index < TotalPlayers; index++)
{
Console.WriteLine("Enter player {0}'s name:", index + 1);
PlayerList.Add(new NameVariable
{
Name = Console.ReadLine(),
ID = index
});
}
// string player1 = ???
// string player2 = ???
// and so on for 12-16 players
}
else
{
Console.WriteLine("Please enter a value between 12 and 16.");
}
}
}
}
I know that a foreach loop can be used to display all of the variables in the NameVariable class. Would just like to know how to assign each variable to a different string.
Before using the class I just used the list which worked by using
string player1 = PlayerList[0];
string player2 = PlayerList[1];
// and so on for the remaining players
Thanks in advance!
it's just
string player1 = PlayerList[0].Name;
string player2 = PlayerList[1].Name;
...
Essentially your list contains NameVariable objects. PlayerList[index] gives you the object, and .Name gives you the property value of the object.
If you want a specific player name by a specific ID number, you can use LINQ (just to give you a hint)
string player = PlayerList.Where(p => p.ID == WhateverIDNumber).First().Name;
While the answer to your immediate question, i.e., how to access properties of a class object, is as others have shown, I feel like this code has a bigger problem. That is you're trying to do too much in one function, namely, Main(). So I advice to in fact try and refactor your code so that one function does one thing. Something like:
public static int GetNumberOfPlayers()
{
Console.Write("Enter number of players: ");
int totalPlayers;
while (!Int32.TryParse(Console.ReadLine(), out totalPlayers))
{
Console.WriteLine("Value must be numeric.");
}
return totalPlayers;
}
public static List<NameVariable> GetPlayerList(int num)
{
var list = new List<NameVariable>();
for (int i = 0; i < num; i++)
{
Console.WriteLine("Enter player {0}'s name:", i + 1);
list.Add(new NameVariable
{
Name = Console.ReadLine(),
ID = i
});
}
return list;
}
public static void DisplayPlayers(List<NameVariable> list)
{
foreach(var player in list)
{
Console.WriteLine("Player {0}, Name: {1}", player.ID, player.Name);
}
}
public static void CantThinkOfAGoodName()
{
while (true)
{
int totalPlayers = GetNumberOfPlayers();
if (totalPlayers > 16 || totalPlayers < 12)
{
Console.WriteLine("Please enter a value between 12 and 16.");
}
else
{
var playerList = GetPlayerList(totalPlayers);
DisplayPlayers(playerList);
break;
}
}
}
public static void Main()
{
CantThinkOfAGoodName();
Console.ReadLine();
}
Not sure if it helps but you can use an indexer to get players by name.
public NameVariable this[string name]
Let's say you create a class for the colection
public class NameColection : List<NameVariable>
{
public NameVariable this[string name]
{
get
{
return this.FirstOrDefault(n => n.Name == name);
}
}
}
Then you access players by name
var players = new NameColection()
{
new NameVariable() { ID = 1 , Name = "John" },
new NameVariable() { ID = 2 , Name = "Paul" },
new NameVariable() { ID = 3 , Name = "George" },
new NameVariable() { ID = 4 , Name = "Ringo" }
};
var player1 = players["John"];
As NameColection inhertits from List, you will be able to add, remove or modify items the usual way.

How can I make a List containing Stats that has Values?

Can I make an Array containing stats that has values to them like shown below?
I know this specific code does not work, but is there any way to do something like it?
string[] stats = new string[]
{
Money = 100,
income = 5,
};
And if I would like to see all stats in a list:
foreach (string var in stats)
{
Console.WriteLine(var.ToString());
}
OUTPUT:
Money = 100
Income = 5
And so on...
You need a class called stats and override the ToString method like this:
public class Stats
{
public int Money { get; set; }
public int Income { get; set; }
public override string ToString()
{
return Money + " " + Income;
}
}
And then:
List<Stats> stats = new List<Stats>
{
new Stats
{
Money = 100,
Income = 5
},
new Stats
{
Money = 200,
Income = 10
}
};
foreach (var item in stats)
{
Console.WriteLine(item.ToString());
//Or like this:
Console.WriteLine("Money = {0} , Income = {1}", item.Money , item.Income);
//Or with c#6 Interpolated Strings
Console.WriteLine($"Money = {item.Money}");
Console.WriteLine($"Income = {item.Income}");
}
You could use
Dictionary<string,int> Values = new Dictionary<string,int>();
Values.Add("Money",100);
Values.Add("Income",5);
where key would be(string) money,income etc and value 100, 5(value) etc
You can use a Class:
public class YourClassName
{
public int Money { get; set; }
public int Income { get; set; }
}
Then you can use:
foreach (YourClassName item in items)
{
Console.WriteLine($"Money = {item.Money}");
Console.WriteLine($"Income = {item.Income}");
}
And store it in a list like this:
List<YourClassName> items = new List<YourClassName>();
items.Add(new YourClassName()
{
Income = 5,
Money = 100
});

I can't Read from FileText C#

I have to make a connection between Students,classes, and year like this: One year can have 1 or more classes and 1 class can have 1 or more students.
I made this with a generic list. The problem is that I have to get the information from one .txt file and I don't know how to do it.
My file is like this:
(Year,Class,Name,Surname,Average).
1 314 George Andrew 8
2 324 Popescu Andrei 9
2 323 Andreescu Bogdan 10
3 332 Marin Darius 9
3 332 Constantin Roxana 10
Code:
public class Student
{
public string Name { get; set; }
public string Surname { get; set; }
public int Average { get; set; }
}
}
public class Grupa
{
public int Name { get; set; }
public List<Student> SetStudent { get; set; }
public Grupa()
{
SetStudent = new List<Student>();
}
public void Print()
{
//Console.WriteLine("Grupa: " + this.Name);
Console.WriteLine("Studentii din grupa: ");
foreach (Student s in this.SetStudent)
{
Console.WriteLine(" " + s.Name+ " " + s.Surname + " --- " + s.Average+"\n");
}
}
}
public class An
{
public int Anul { get; set; }
public List<Grupa> SetGrupa { get; set; }
public An()
{
SetGrupa = new List<Grupa>();
}
public void Print()
{
Console.WriteLine("Anul: " + this.Anul);
Console.WriteLine("Grupele din acest an: ");
foreach (Grupa g in this.SetGrupa)
{
Console.WriteLine(" " + g.Name);
}
}
}
string[] lines = System.IO.File.ReadAllLines(#"D:\C#\Tema1\Tema1.txt");
System.Console.WriteLine("Content Tema1.txt= \n");
foreach (string line in lines)
{
Console.WriteLine("\t" + line);
}
Console.WriteLine("\n Close");
System.Console.ReadKey();
}
You can also use the .NET TextFieldParser for that type of flat file:
var studentList = new List<Student>();
var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser("<file path>");
parser.SetFieldWidths(4, 4, 12, 8, 2);
while (!parser.EndOfData)
{
string[] line = parser.ReadFields();
var student = new Student();
student.Year = int.Parse(line[0]);
student.Class = int.Parse(line[1]);
student.Name = line[2].Trim();
student.Surname = line[3].Trim();
student.Average = int.Parse(line[4]);
studentList.Add(student);
}
You just have to setup the field lengths in the SetFieldWidths function.
Your question is a vague one, are you looking for Linq like that:
// Parsing into objects
var data = System.IO.File
.ReadLines(#"D:\C#\Tema1\Tema1.txt")
.Skip(1) //TODO: comment down this line if your file doesn't have a caption
.Select(line => line.Split('\t'))
.Select(items => new { // or "new Student() {" if you've designed a Student class
Year = int.Parse(items[0]),
Class = int.Parse(items[1]),
Name = items[2],
Surname = items[3],
Average = int.Parse(items[4]), //TODO: Is it Int32 or Double?
});
...
// combining back:
String result = String.Join(Environment.NewLine, data
.Select(item => String.Join("\t",
item.Year, item.Class, item.Name, item.Surname, item.Average));
Console.Write(result);
If you want to have total control over what you want to do, I advise to create a class for each individual studet.
A rough approach:
namespace ConsoleApplication1
{
class Student
{
//Members of class
public int Year;
public int Class;
public string FirstName;
public string LastName;
public int Average;
/// <summary>
/// Gets a line and creates a student object
/// </summary>
/// <param name="line">The line to be parsed</param>
public Student(string line)
{
//being parsing
//split by space
List<String> unfiltered = new List<string>(line.Split(' '));
//a list to save filtered data
List<string> filtred = new List<string>();
//filter out empty spaces...
//There exist much smarter ways...but this does the job
foreach (string entry in unfiltered)
{
if (!String.IsNullOrWhiteSpace(entry))
filtred.Add(entry);
}
//Set variables
Year = Convert.ToInt32(filtred[0]);
Class = Convert.ToInt32(filtred[1]);
FirstName = filtred[2];
LastName = filtred[3];
Average = Convert.ToInt32(filtred[4]);
}
}
class Program
{
static void Main(string[] args)
{
var data = System.IO.File.ReadAllLines(#"d:\data.txt");
//a list to hold students
List<Student> students = new List<Student>();
foreach (var line in data)
{
//create a new student and add it to list
students.Add(new Student(line));
}
//to test, write all names
foreach (var student in students)
{
Console.WriteLine(student.FirstName + " " + student.LastName + Environment.NewLine);
}
//you can calculate average of all students averages!
int sum = 0;
for (int i = 0; i < students.Count; i++)
{
sum += students[i].Average;
}
//print average of all students
Console.WriteLine("Average mark of all students: " + (sum / students.Count));
Console.ReadKey();
}
}
}

Using the highest value from one list to sort the second list.

There are two lists.
I have a list of students, made like this
List<Student> students = new List<Student>();
The properties of each student object in the list are firstName, LastName, and Fees[].
Fees is an array that holds a set of fees for each student in the list.
I made a second list like this:
List<double> totals = new List<double>();
I loop through the list of students and add up the fees for each. Then I add the totals for each student to the totals list (My second list).
Now I need to sort the students list so the highest total amount due in fees is at the beginning. In other words, I need to sort students using the highest value in totals. I can get the highest value out of totals like this:
double highestTotalAmountDue = totals.Max();
How do I use this highestTotalAmountDue value to sort the students list so that the student with the highest fee total is at the beginning of the list??
Just to clarify, I only need to add the student with the highest fee total at the top of the list. The rest can remain in the same order.
Here is my code so far:
List<double> totals = new List<double>();
double tempTotal = 0;
Lis<Student> students = new Lis<Student>();
// populate the students list
foreach (var item in students)
{
for (var i = 0; i < resultSet[0].Fees.Length; i++)
{
tempTotal += item.Fees[i].Amount;
}
totals.Add(tempTotal);
tempTotal = 0;
}
double highestTotalAmountDue = totals.Max();
// now what to do to sort the students list by highestTotalAmountDue to put the student with the highest fee due at the top????
Please help. Thanks in advance.
If i've got it right:
var orderedStudents = students
.OrderByDescending(s => s.Fees.Sum(f => f.Amount) == highestTotalAmountDue);
This will put the max-fee-amount student(s) at the top, the other will remain unordered.
Do away with the list of totals. You can track the highest total as follows, then re-insert the student at the top of the list.
List<Student> students = new List<Student>();
// populate the students list
// Mark the student with the highest total as we find him.
Student highestTotalStudent = null;
var highestTotal = 0.0;
foreach (var student in students)
{
var tempTotal = 0.0;
for (var i = 0; i < resultSet[0].Fees.Length; i++)
{
tempTotal += student.Fees[i].Amount;
}
if (tempTotal > highestTotal)
{
// We have a new winner
highestTotal = tempTotal;
highestTotalStudent = student;
}
}
// Finally, remove the located student, and re-insert her at the top of the list
students.Remove(highestTotalStudent);
students.Insert(0, highestTotalStudent);
double highestTotalAmountDue = totals.Max();
int highestIndex = totals.IndexOf(highestTotalAmountDue );
var student = student[highestIndex];
students.RemoveAt(highestIndex);
students.Insert(highestIndex,studet);
I think the key code is...
var studentToMove = students.FirstOrDefault(x => x.FeesTotal == students.Max(s => s.FeesTotal));
students.Remove(studentToMove);
students.Insert(0, studentToMove);
class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>()
{
new Student()
{
FirstName = "Joe", LastName = "Smith",
Fees = new Fee[]
{
new Fee()
{
Amount = 55
},
new Fee()
{
Amount = 100
}
}
},
new Student()
{
FirstName = "Jane", LastName = "Smith",
Fees = new Fee[]
{
new Fee()
{
Amount = 400
},
new Fee()
{
Amount = 32
}
}
},
new Student()
{
FirstName = "Sam", LastName = "Smith",
Fees = new Fee[]
{
new Fee()
{
Amount = 3
},
new Fee()
{
Amount = 10
}
}
}
};
var studentToMove = students.FirstOrDefault(x => x.FeesTotal == students.Max(s => s.FeesTotal));
students.Remove(studentToMove);
students.Insert(0, studentToMove);
foreach (var student in students)
{
Console.WriteLine("Student: " + student.FirstName + " " + student.LastName);
}
}
}
class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Fee[] Fees { get; set; }
public decimal FeesTotal
{
get
{
if (Fees == null || Fees.Length == 0)
return 0;
return Fees.Sum(x => x.Amount);
}
}
}
class Fee
{
public decimal Amount { get; set; }
}

Categories