Best way to compare list in C #

I have two lists:

List<string> names; and List<Student> stud; 

Student class has 3 properties

 ID Name Section 

Now I want to execute a List<string> loop and compare each element with the Name property in List<Student> and perform operations if they are not equal

I tried iterating over the names and comparing each value with a hairpin.

But I thought there must be some better way to do this using LINQ , or I should use YIELD .

thanks

+6
source share
3 answers

This is not very clear from your description, but if you want "all students whose names were not on the list", you can definitely use LINQ:

 var studentsWithoutListedNames = stud.Where(s => !names.Contains(s.Name)); foreach (var student in studentsWithoutListedNames) { // Whatever... } 
+6
source

If your intention is not what John describes, but more, to compare the list of names with the list of student names and find the differences:

 var invalidStudents = names.Zip(stud, (name, student) => new {name, student}). Where(item => (item.name != item.student.Name)); if (invalidStudents.Any()) // Or foreach... { ... } 

eg:

 var names = new string[] { "John", "Mary" }; var stud = new Student[] { new Student(1, "John", "IT"), new Student(2, "Jack", "Math") }; var invalidStudents = names.Zip(stud, (name, student) => new {name, student}). Where(item => (item.name != item.student.Name)); foreach (var item in invalidStudents) { Console.WriteLine(item.name); } 

Gotta write mary

+2
source

Another good way to do this:

 var notOnList = students.Except(from student in students join name in names on student.Name equals name select student); foreach(var student in notOnList) { ... } 
0
source

Source: https://habr.com/ru/post/944977/


All Articles