Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way for Comparing List in c#

Tags:

c#

list

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

like image 795
user2067567 Avatar asked May 14 '13 13:05

user2067567


People also ask

How do I compare two unordered lists?

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) .

How can I compare two lists online?

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.

How do you make every item compare the rest items in a list Python?

Using All() The all() method applies the comparison for each element in the list.


2 Answers

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...
}
like image 182
Jon Skeet Avatar answered Oct 01 '22 21:10

Jon Skeet


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

like image 20
vc 74 Avatar answered Oct 01 '22 21:10

vc 74