How to print out all the persons and their pets, using Linq. I only want to print out persons who have pets.
Prefer result be like:
Kate Bed:
Rex
Sally
My not working solution is here:
class Program
{
static void Main(string[] args)
{
result();
}
static void result() {
var list = StaticGenator.getPersons().Where(x => x.Pets != null);
foreach (var person in list)
{
Console.WriteLine(person.Firstname + " " + person.Lastname + ":");
foreach(var pet in list){
Console.WriteLine(" " + pet.Pets);
}
}
}
What i get is:
Kate Bed:
system.collection.generic.list'1[MainLibrary.Pet]
system.collection.generic.list'1[MainLibrary.Pet]
Here is the code to understand what I am asking:
Data is held here:
public static class StaticGenator
{
public static List<Person> getPersons()
{
List<Person> persons = new List<Person>();
persons.Add(new Person() { Firstname = "Sam", Lastname = "Car", BirthDate = new DateTime(2001, 01, 01), PersonId = 1, Sex = Sex.Man });
persons.Add(new Person() { Firstname = "Kate", Lastname = "Bed", BirthDate = new DateTime(1995, 11, 11), PersonId = 2, Sex = Sex.Woman, Pets = new List<Pet>() { new Pet { Firstname = "Rex", BirthDate = new DateTime(2007, 1, 1), Sex = Sex.Man, PetId = 1 }, new Pet { Firstname = "Sally", BirthDate = new DateTime(2004, 2, 1), Sex = Sex.Woman, PetId = 2 } } });
return persons;
}
}
Person Class:
public class Person
{
public int PersonId { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public DateTime BirthDate { get; set; }
public Sex Sex{ get; set; }
public int Age {
get
{
var age= DateTime.Now.Year - BirthDate.Year;
if (DateTime.Now.Day >= BirthDate.Day && DateTime.Now.Month >= BirthDate.Month)
return age;
else
return age- 1;
}
}
public List<Pet> Pets { get; set; }
}
Pet Class:
public class Pet
{
public int PetId { get; set; }
public String Firstname { get; set; }
public Sex Sex { get; set; }
public DateTime BirthDate { get; set; }
public int Age { get; set; }
}
Sex enum:
public enum Sex{
Man,
Woman
}
foreach (var person in list)
{
Console.WriteLine(person.Firstname + " " + person.Lastname + ":");
foreach(var pet in person.Pets) // iterate over Pets of person
{
Console.WriteLine(" " + pet.Firstname); // write pet's name
}
}
Keep in mind - you can have problem if somebody will add null pet to pets collection or if there is empty pets list. So, probably correct query to get persons with pets is:
var peopleWithPets = from p in StaticGenator.getPersons()
where p.Pets != null &&
p.Pets.Any() &&
p.Pets.All(x => x != null)
select p;
Also use string formatting:
foreach (var person in peopleWithPets)
{
Console.WriteLine("{0} {1}:", person.Firstname, person.Lastname);
foreach(var pet in person.Pets)
Console.WriteLine("\t{0}", pet.Firstname);
}
Also I suggest you to follow Capitalization Styles recommended by MicroSoft.
foreach(var pet in list)
{
Console.WriteLine(" " + pet.Pets);
}
Should be:
foreach(var pet in person.Pets)
{
Console.WriteLine(" " + pet.FirstName);
}
You have to iterate over the pet collection of the current user that is being iterated.
Suppose you have some list (you mentioned above) with your datastructure
List<Person> persons = new List<Person>();
persons.Add(new Person() { Firstname = "Sam", Lastname = "Car", BirthDate = new DateTime(2001, 01, 01), PersonId = 1, Sex = Sex.Man });
persons.Add(new Person() { Firstname = "Kate", Lastname = "Bed", BirthDate = new DateTime(1995, 11, 11), PersonId = 2, Sex = Sex.Woman, Pets = new List<Pet>() { new Pet { Firstname = "Rex", BirthDate = new DateTime(2007, 1, 1), Sex = Sex.Man, PetId = 1 }, new Pet { Firstname = "Sally", BirthDate = new DateTime(2004, 2, 1), Sex = Sex.Woman, PetId = 2 } } });
You can very easily filter as well as write to console with these 4 lines of code
persons.Where(p => p.Pets != null && p.Pets.Any()).ToList().ForEach(p =>
{
Console.WriteLine(p.Firstname + " " + p.Lastname + "\n");
p.Pets.ForEach(pt => Console.WriteLine(pt.Firstname));
});
var output = String.Join("\n", persons.Select(person => $"{person.Firstname} {person.Lastname}"));
Output:
Sam Car
Kate Bed
Related
I've created a list of courses that students are enrolled in. However, I can't figure out how to access the objects from the list in the Main. Below, I've tried to get the Student-Id and pull the information from there, but it isn't working. I'm new to coding please help
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace Jvstt_College
{
class Admin
{
##
## Dictionary<int, Student> studentList = new Dictionary<int, Student>();
Dictionary<int, Professor> professorList = new Dictionary<int, Professor>();
List<Course> courseList = new List<Course>();
Dictionary<int, Student> studentCourses = new Dictionary<int, Student>();
public Dictionary<int, Student> StudentList()
{
var Student1 = new Student() { FirstName = "Tom", LastName = " Jones", Password = "Test", EnrollmentId = 111111};
var Student2 = new Student() { FirstName = "Mark", LastName = " Thomas", Password = "Grace", EnrollmentId = 101203 };
var Student3 = new Student() { FirstName = "Jake", LastName = " Riley", Password = "SavedbyChrist1", EnrollmentId = 568903 };
var Student4 = new Student() { FirstName = "Olivia", LastName = " Beckam", Password = "GodisGood", EnrollmentId = 951357 };
var Student5 = new Student() { FirstName = "Myrai", LastName = " Bailey", Password = "ChildofGod", EnrollmentId = 741369 };
var Student6 = new Student() { FirstName = "Majea", LastName = " Bailey", Password = "CoastLand", EnrollmentId = 852146 };
studentList.Add(111111, Student1);
studentList.Add(101203, Student2);
studentList.Add(568903, Student3);
studentList.Add(951357, Student4);
studentList.Add(741369, Student5);
studentList.Add(852146, Student6);
return studentList;
}
public Dictionary<int, Professor> ProfessorList()
{
professorList.Add(654321, new Professor { FirstName = "Grace", LastName = "Riley", Password = "Gracey1983", EnrollmentId = 654321 });
enter code here professorList.Add(852963, new Professor { FirstName = "Liam", LastName = "Beckam", Password = "Password", EnrollmentId = `enter code here`852963 });
professorList.Add(359861, new Professor { FirstName = "Martha", LastName = "Hart", Password = "QwertYy00", EnrollmentId = 359861 });
professorList.Add(612832, new Professor { FirstName = "George", LastName = "Washington", Password = "Kid$nExtD00r", EnrollmentId = 612832 });
return professorList;
}
public List<Course> CourseList()
{
var Accounts = new Course() { CourseID = 101, CourseName = " Accounts " };
var Bio_Psychology = new Course() { CourseID = 102, CourseName = " Bio_Psychology " };
var Business = new Course() { CourseID = 103, CourseName = " Business " };
var Chemistry = new Course() { CourseID = 104, CourseName = " Chemistry " };
var CSWDCA = new Course() { CourseID = 105, CourseName = " Computer Science/Web Design/Cybersecurity Accounts" };
var Psychology = new Course() { CourseID = 106, CourseName = " Psychology " };
var Statistics = new Course() { CourseID = 107, CourseName = " Statistics " };
var Advance_Math = new Course() { CourseID = 108, CourseName = "Advance Math" };
courseList.Add(Accounts);
courseList.Add(Bio_Psychology);
courseList.Add(Business);
courseList.Add(Chemistry);
courseList.Add(CSWDCA);
courseList.Add(Psychology);
courseList.Add(Statistics);
courseList.Add(Advance_Math);
return courseList;
}
public Dictionary<int, Student> StudentEnrollments()
{
var Student1 = studentList[111111];
{
if(Student1.Courses == null)
{
Student1.Courses = new List<Course>();
Student1.Courses?.Add(courseList[0]);
Student1.Courses?.Add(courseList[2]);
Student1.Courses?.Add(courseList[4]);
}
}
var Student2 = studentList[101203];
{
if(Student2.Courses == null)
{
Student2.Courses = new List<Course>();
Student2.Courses?.Add(courseList[1]);
Student2.Courses?.Add(courseList[4]);
Student2.Courses?.Add(courseList[5]);
Student2.Courses?.Add(courseList[6]);
Student2.Courses?.Add(courseList[7]);
}
}
var Student3 = studentList[568903];
{
if (Student3.Courses == null)
{
Student3.Courses = new List<Course>();
Student3.Courses?.Add(courseList[1]);
Student3.Courses?.Add(courseList[4]);
}
}
var Student4 = studentList[951357];
{
if (Student4.Courses == null)
{
Student4.Courses = new List<Course>();
Student4.Courses?.Add(courseList[1]);
Student4.Courses?.Add(courseList[5]);
Student4.Courses?.Add(courseList[7]);
}
}
var Student5 = studentList[741369];
{
if (Student5.Courses == null)
{
Student5.Courses = new List<Course>();
Student5.Courses?.Add(courseList[0]);
Student5.Courses?.Add(courseList[2]);
Student5.Courses?.Add(courseList[3]);
Student5.Courses?.Add(courseList[6]);
Student5.Courses?.Add(courseList[7]);
}
}
var Student6 = studentList[852146];
{
if (Student6.Courses == null)
{
Student6.Courses = new List<Course>();
Student6.Courses?.Add(courseList[0]);
Student6.Courses?.Add(courseList[1]);
Student6.Courses?.Add(courseList[2]);
Student6.Courses?.Add(courseList[3]);
Student6.Courses?.Add(courseList[4]);
Student6.Courses?.Add(courseList[5]);
Student6.Courses?.Add(courseList[6]);
}
}
studentCourses.Add(111111,Student1);
studentCourses.Add(101203,Student2);
studentCourses.Add(568903,Student3);
studentCourses.Add(951357,Student4);
studentCourses.Add(741369,Student5);
studentCourses.Add(852146,Student6);
return studentCourses;
}
}
}
}
First, let's declare the Professor, Student and Course classes. Since Professor and Student have similar properties and since they both are persons, it makes sense to derive them both from an abstract Person class. An abstract class cannot be instantiated.
abstract class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public int EnrollmentId { get; set; }
}
class Professor : Person
{
}
class Student : Person
{
public List<Course> Courses { get; } = new List<Course>();
}
class Course
{
public int CourseID { get; set; }
public string CourseName { get; set; }
}
In class Student I created the Courses list as read-only property and initialized it with a property initializer. This saves you from having to do something like if (Student2.Courses == null) { Student2.Courses = new List<Course>(); ... } later.
You have several method initializing lists and dictionaries. Those should declare and create the collections they return. Otherwise, if the collections are declared in a surrounding scope, the return statement would not be required and the responsibilities would not be clear. Add also, a dictionary is not a list. Since these methods do rely on instance fields anymore, we make them static (and simplify them):
// In class Admin
private static Dictionary<int, Student> CreateStudents()
{
return new Dictionary<int, Student> {
{ 111111, new Student { FirstName = "Tom", LastName = " Jones", Password = "Test", EnrollmentId = 111111 } },
{ 101203, new Student { FirstName = "Mark", LastName = " Thomas", Password = "Grace", EnrollmentId = 101203 } },
{ 568903, new Student { FirstName = "Jake", LastName = " Riley", Password = "SavedbyChrist1", EnrollmentId = 568903 } },
{ 951357, new Student { FirstName = "Olivia", LastName = " Beckam", Password = "GodisGood", EnrollmentId = 951357 } },
{ 741369, new Student { FirstName = "Myrai", LastName = " Bailey", Password = "ChildofGod", EnrollmentId = 741369 } },
{ 852146, new Student { FirstName = "Majea", LastName = " Bailey", Password = "CoastLand", EnrollmentId = 852146 } }
};
}
private static Dictionary<int, Professor> CreateProfessors()
{
return new Dictionary<int, Professor> {
{ 654321, new Professor { FirstName = "Grace", LastName = "Riley", Password = "Gracey1983", EnrollmentId = 654321 } },
{ 852963, new Professor { FirstName = "Liam", LastName = "Beckam", Password = "Password", EnrollmentId = 852963 } },
{ 359861, new Professor { FirstName = "Martha", LastName = "Hart", Password = "QwertYy00", EnrollmentId = 359861 } },
{ 612832, new Professor { FirstName = "George", LastName = "Washington", Password = "Kid$nExtD00r", EnrollmentId = 612832 } }
};
}
private static List<Course> CreateCourses()
{
return new List<Course> {
new Course { CourseID = 101, CourseName = "Accounts" },
new Course { CourseID = 102, CourseName = "Bio_Psychology" },
new Course { CourseID = 103, CourseName = "Business" },
new Course { CourseID = 104, CourseName = "Chemistry" },
new Course { CourseID = 105, CourseName = "Computer Science/Web Design/Cybersecurity Accounts" },
new Course { CourseID = 106, CourseName = "Psychology" },
new Course { CourseID = 107, CourseName = "Statistics" },
new Course { CourseID = 108, CourseName = "Advance Math" }
};
}
Now, we can declare and initialize the collections like this:
class Admin
{
public readonly Dictionary<int, Student> students = CreateStudents();
public readonly Dictionary<int, Professor> professors = CreateProfessors();
public readonly List<Course> courses = CreateCourses();
...
}
I made them read-only. This only means that we cannot assign it another collection later. The collections themselves are still read/write.
We do not need another collection studentCourses, we can directly add the courses to the students in our existing students dictionary.
If we declare an instance method EnrollStudents in class Admin, then it can access the fields of this class.
public void EnrollStudents()
{
Student student = students[111111];
student.Courses.Add(courses[0]);
student.Courses.Add(courses[2]);
student.Courses.Add(courses[4]);
student = students[101203]; // It is okay to reuse the student variable
student.Courses.Add(courses[1]);
student.Courses.Add(courses[4]);
student.Courses.Add(courses[5]);
student.Courses.Add(courses[6]);
student.Courses.Add(courses[7]);
student = students[568903];
student.Courses.Add(courses[1]);
student.Courses.Add(courses[4]);
student = students[951357];
student.Courses.Add(courses[1]);
student.Courses.Add(courses[5]);
student.Courses.Add(courses[7]);
student = students[741369];
student.Courses.Add(courses[0]);
student.Courses.Add(courses[2]);
student.Courses.Add(courses[3]);
student.Courses.Add(courses[6]);
student.Courses.Add(courses[7]);
student = students[852146];
student.Courses.Add(courses[0]);
student.Courses.Add(courses[1]);
student.Courses.Add(courses[2]);
student.Courses.Add(courses[3]);
student.Courses.Add(courses[4]);
student.Courses.Add(courses[5]);
student.Courses.Add(courses[6]);
}
Note that we do not have to return anything. Since classes are reference types, all the students in the original students dictionary have now been updated with courses. Of course we must call this method somewhere (probably in Main).
But we can simplify this method with a new helper method, because we have a lot of repetitions we can avoid:
private void AddStudentCourses(Student student, params int[] courseIndexes)
{
foreach (int index in courseIndexes) {
student.Courses.Add(courses[index]);
}
}
public void EnrollStudents()
{
AddStudentCourses(students[111111], 0, 2, 4);
AddStudentCourses(students[101203], 1, 4, 5, 6, 7);
AddStudentCourses(students[568903], 1, 4);
AddStudentCourses(students[951357], 1, 5, 7);
AddStudentCourses(students[741369], 0, 2, 3, 6, 7);
AddStudentCourses(students[852146], 0, 1, 2, 3, 4, 5, 6);
}
Test:
var admin = new Admin();
admin.EnrollStudents();
var orderedStudents = admin.students.Values
.OrderBy(s => s.LastName)
.ThenBy(s => s.FirstName);
foreach (var student in orderedStudents) {
Console.WriteLine($"{student.LastName} {student.FirstName} ({student.EnrollmentId})");
IOrderedEnumerable<Course> orderedCourses = student.Courses.OrderBy(c => c.CourseName);
foreach (var course in orderedCourses) {
Console.WriteLine($" {course.CourseName} ({course.CourseID})");
}
Console.WriteLine();
}
Prints
Bailey Majea (852146)
Accounts (101)
Bio_Psychology (102)
Business (103)
Chemistry (104)
Computer Science/Web Design/Cybersecurity Accounts (105)
Psychology (106)
Statistics (107)
Bailey Myrai (741369)
Accounts (101)
Advance Math (108)
Business (103)
Chemistry (104)
Statistics (107)
Beckam Olivia (951357)
Advance Math (108)
Bio_Psychology (102)
Psychology (106)
Jones Tom (111111)
Accounts (101)
Business (103)
Computer Science/Web Design/Cybersecurity Accounts (105)
Riley Jake (568903)
Bio_Psychology (102)
Computer Science/Web Design/Cybersecurity Accounts (105)
Thomas Mark (101203)
Advance Math (108)
Bio_Psychology (102)
Computer Science/Web Design/Cybersecurity Accounts (105)
Psychology (106)
Statistics (107)
When using LiteCollection's instance method Find(), I passed a predicate into it as a parameter. This is the Find() method: stus.Find(s => s.Birthday.Year <= 1996);, and full code here:
Student.cs:
public class Student
{
public ObjectId ID { get; set; }
public string Name { get; set; }
public int Grade { get; set; }
public DateTime Birthday { get; set; }
}
Program.cs:
class Program
{
static void Main(string[] args)
{
using (var db = new LiteDatabase("test.db"))
{
LiteCollection<Student> stus = db.GetCollection<Student>("students");
List<Student> studentList = new List<Student>()
{
new Student() {Name = "Nguyen Hoang Nguyen", Birthday = new DateTime(1997, 6, 3), Grade = 8},
new Student() {Name = "Nguyen Anh Tuan", Birthday = new DateTime(1997, 7, 12), Grade = 8},
new Student() {Name = "Pham Van Hung", Birthday = new DateTime(1996, 3, 26), Grade = 9}
};
stus.Insert(studentList);
var filteredStudents = stus.Find(s => s.Birthday.Year <= 1996);
Console.WriteLine("Student who has birth year before 1996:");
foreach (Student filteredStudent in filteredStudents)
{
Console.WriteLine($"- {filteredStudent.Name}, grade: {filteredStudent.Grade}");
}
Console.ReadKey();
stus.Delete(_ => true);
}
}
}
But filteredStudents doesn't contain any student, only "Student who has birth year before 1996:" line was printed to the console. So is anything here wrong or I missed something here? Thank you for reading my question.
You can not do that in liteDB
You must create a DateTime Object
var d = new DateTime(1996);
var filteredStudents = stus.Find(s => s.Birthday.Year <= d);
Consider an entity named Employee which contains id,age and name as properties
I have two lists containing the Employee details
I have to compare the two lists excluding the id column
Please help with your suggestions
This will yield all the entries that are the same in both lists, ignoring the Id Property of your Employee:
var employees1 = new List<Employee>
{
new Employee(1, "Thomas", 12),
new Employee(2, "Alex", 24),
new Employee(3, "Tobias", 13),
new Employee(4, "Joshua", 12),
new Employee(5, "Thomas", 24)
};
var employees2 = new List<Employee>
{
new Employee(1, "Thomas", 12),
new Employee(2, "Yu", 24),
new Employee(3, "Max", 13),
new Employee(4, "Joshua", 30),
new Employee(5, "Maico", 13)
};
var duplicates = employees1.Intersect(employees2, new EmployeeComparer());
class EmployeeComparer : IEqualityComparer<Employee>
{
public bool Equals(Employee employee1, Employee employee2)
{
if (Object.ReferenceEquals(employee1, null) || Object.ReferenceEquals(employee2, null) ||
Object.ReferenceEquals(employee1, employee2)) return false;
return employee1.Name == employee2.Name && employee1.Age == employee2.Age;
}
public int GetHashCode(Employee employee)
{
return 0;
}
}
class Employee
{
public Employee(int id, string name, int age)
{
Id = id;
Name = name;
Age = age;
}
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
As the post is tagged with LINQ I have used that in my answer.
static void Main(string[] args)
{
var list1 = new List<Person>();
var list2 = new List<Person>();
list1.Add(new Person(1, "james", "moon"));
list1.Add(new Person(1, "bob", "bar"));
list1.Add(new Person(1, "tim", "lane"));
list1.Add(new Person(1, "fizz", "sea"));
list2.Add(new Person(1, "buzz", "space"));
list2.Add(new Person(1, "james", "moon"));
var result = findDuplicates(list1, list2);
}
public static List<Person> findDuplicates(List<Person> l1, List<Person> l2)
{
return l1.Where(p => l2.Any(z => z.FName == p.FName && z.Addre == p.Addre)).ToList();
}
Person Class
public class Person
{
private int id;
private string fName;
private string addre;
public string Addre
{
get { return addre; }
set { addre = value; }
}
public string FName
{
get { return fName; }
set { fName = value; }
}
public int ID
{
get { return id; }
set { id = value; }
}
public Person(int i, string f, string a)
{
ID = i;
FName = f;
Addre = a;
}
}
Assuming Employee class:
class Employee
{
public int id { get; set; }
public int age { get; set; }
public string name { get; set; }
}
You can simply use Intersect :
var list1 = new List<Employee> {
new Employee{ id=2 , age=23, name="Hari"},
new Employee{ id=3 , age=10, name="Joe"},
new Employee{ id=4 , age=29, name="Daniel"},
};
var list2 = new List<Employee> {
new Employee{ id=1 , age=23, name="Hari"},
new Employee{ id=5 , age=10, name="Joe"},
new Employee{ id=6 , age=29, name="Daniel"},
};
var intersect = list1.Select(e => new { e.age, e.name }).Intersect(list2.Select(e => new { e.age, e.name })).ToList();
I have three different lists including students, courses, and grades. What I want to do is to use some of courses and students properties in grades variable. Here is my code:
namespace educationsystem
{
public class student
{
public int scode { get; set; }
public string name { get;set;}
public string lastname {get;set;}
public long phone {get;set;}
}
public class course
{
public int code { get; set;}
public string name { set; get;}
public int unit { set; get;}
}
public class grade
{
public student studentinfo { get; set; }
public course courseinfo { get; set; }
public double value { get; set; }
public int term { get; set; }
}
public class education
{
}
class Program
{
static void Main(string[] args)
{
List<student> Students = new List<student>();
List<course> courses = new List<course>();
List<int> grades = new List<int>();
Students.Add(new student { scode=1,name = "mahta", lastname = "sahabi", phone = 3244 });
Students.Add(new student { scode=2, name = "niki", lastname = "fard", phone = 5411 });
Students.Add(new student { scode=3, name = "hana", lastname = "alipoor", phone = 6121 });
courses.Add(new course { code = 1, name = "Mathemathics", unit = 3 });
courses.Add(new course { code = 2, name = "physics", unit = 3 });
courses.Add(new course { code = 3, name = "computer", unit = 3 });
Students.ForEach((student) => { Console.WriteLine(student.scode+" "+student.name + " " + student.lastname + " " + student.phone); });
courses.ForEach((course) => { Console.WriteLine(course.code + " " + course.name + " " + course.unit); });
Console.ReadKey();
}
I would like to print the grades like:
mahta sahabi mathematics 20.
How can I do such thing?
To hardcode a grade and print it, you can use:
List<grade> grades = new List<grade>(); // instead of List<int>
// ...
grades.Add(new grade
{
studentinfo = Students.Where(s => s.scode == 1).First(),
courseinfo = courses.Where(c => c.code == 1).First(),
value = 20.0d,
term = 1
});
// ...
grades.ForEach((grade) => { Console.WriteLine(grade.studentinfo.name + " " + grade.studentinfo.lastname + " " + grade.courseinfo.name + " " + grade.value); });
Is that what you were looking for?
You'll need to associate the appropriate students and courses when you create the grades collection. You'll then be able to access the assocation by navigating it
grade.studentinfo.name
and
grade.courseinfo.name
Since there will likely be a many : many relationship between students and courses, how about initializing your objects through a Dictionary, to allow easy identification of each student and course when you define the associations to grade:
var students = new []
{
new student { scode=1,name = "mahta", lastname = "sahabi", phone = 3244 },
new student { scode=2, name = "niki", lastname = "fard", phone = 5411 },
... etc
}.ToDictionary(s => s.scode);
var courses = new []
{
new course { code = 1, name = "Mathemathics", unit = 3 },
....
}.ToDictionary(c => c.code);
var grades = new []
{
new grade { term = 1, value = 53, student = students[1], course = courses[2] },
new grade { term = 2, value = 99, student = students[1], course = courses[1] },
...
}
You'll then be able to print these out like so:
foreach(var grade in grades)
{
Console.WriteLine($"{grade.studentinfo.name} {grade.courseinfo.name} {grade.value}" );
}
Have a collection
List<<KeyValuePair<string, Person>>
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int MealType { get; set; }
}
patientEffort.Add("1", new Person() { FirstName = "Raja", LastName = "Ram", MealType = 2 });
patientEffort.Add("2", new Person() { FirstName = "Vijay", LastName = "Anthony", MealType = 1 });
patientEffort.Add("2", new Person() { FirstName = "Vijay", LastName = "Anthony", MealType = 2 });
patientEffort.Add("2", new Person() { FirstName = "Vijay", LastName = "Anthony", MealType = 3 });
patientEffort.Add("3", new Person() { FirstName = "Dr", LastName = "APJ", MealType = 1 });
patientEffort.Add("3", new Person() { FirstName = "Dr", LastName = "APJ", MealType = 2 });
patientEffort.Add("3", new Person() { FirstName = "Dr", LastName = "APJ", MealType = 3 });
patientEffort.Add("3", new Person() { FirstName = "Dr", LastName = "APJ", MealType = 4 });
List<int> _listMealType = new List<int>();
If _listMealType= [2] passed then Result will be
{Key: "1", FirstName = "Raja", LastName = "Ram"}
{Key: "2", FirstName = "Vijay", LastName = "Anthony"}
{Key: "3", FirstName = "Dr", LastName = "APJ"}
If _listMealType= [1,2,3] passed then Result will be
{Key: 2, FirstName = "Vijay", LastName = "Anthony"}
{Key: 3, FirstName = "Dr", LastName = "APJ"}
If _listMealType= [1,2,3,4] passed then Result will be
{Key: "3", FirstName = "Dr", LastName = "APJ"} only
Key may be string or int that doesn't matter. May I have linq query for this scenario. I have used All method is linq but not worked.
var query = patientEffort.Where(d => _listMealType.All(x => x == d.Value.MealType)).Select(d => d.Key);
Could you please help me in solving the query issue as soon as possible.
I hope it helps:
var patients = patientEffort.GroupBy(x => x.Value.FirstName);
var result = (from patient in patients let res = patient.Select(note => note.Value.MealType).ToList() where _listMealType.Intersect(res).Count() == _listMealType.Count select patient.First()).ToList();
Here is variant without linq using:
var patients = patientEffort.GroupBy(x => x.Value.FirstName); // group patients by name
foreach (var patient in patients)
{
var res = new List<int>();
foreach (var note in patient) // collect all meal types of current patient
res.Add(note.Value.MealType);
if (_listMealType.Intersect(res).Count() == _listMealType.Count) // if intersection count equal to source meal list - it's our patient.
result.Add(patient.First()); // add information about patient. because we need only name - we can use first record in list.
}