I have two list say
List<string> names; and List<Student> stud;
Student Class has 3 properties
ID
Name
Section
Now i want to loop through List<string>
and compare each item with Name property in List<Student>
and want to perform operations if they are not equal
I tried looping through names and comparing each values to stud.
But i thought there must be some better way of doing this with LINQ
or should i be using YIELD
.
Thanks
How do I compare two unordered lists? To check if two unordered lists x and y are identical, compare the converted sets with set(x) == set(y) . However, this loses all information about duplicated elements. To consider duplicates, compare the sorted lists with sorted(x) == sorted(y) .
Multiple List Comparator is a free online tool made to compare two or more item lists, find the shared items (dataset intersections), and output both tabular and graphical results. It will generate a customizable Venn diagram for up to five lists and display a matrix of all pairwise intersections.
Using All() The all() method applies the comparison for each element in the list.
It's not very clear from your description, but if you want "all students whose names aren't in the list" you can definitely use LINQ:
var studentsWithoutListedNames = stud.Where(s => !names.Contains(s.Name));
foreach (var student in studentsWithoutListedNames)
{
// Whatever...
}
If your intention is not what Jon describes but more to compare the list of names with the list of student names and find differences:
var invalidStudents = names.Zip(stud, (name, student) => new {name, student}).
Where(item => (item.name != item.student.Name));
if (invalidStudents.Any()) // Or foreach...
{
...
}
for example:
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);
}
Should write Mary
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With