I want to compare items in a list, but I don't want it to be compared to itself. How do I do that? My code:
var students = new List<Student>() {
new Student(){ Id = 1, Name="Bill"},
new Student(){ Id = 2, Name="Steve"},
new Student(){ Id = 3, Name="Ram"},
};
for (int i=0; i<students.Count(); i )
{
for (int x = 0; x < students.Count(); x )
{
Console.WriteLine(students[i].Name " -- " students[x].Name);
}
}
this code returns...
Bill -- Bill
Bill -- Steve
Bill -- Ram
Steve -- Bill
Steve -- Steve
Steve -- Ram
Ram -- Bill
Ram -- Steve
Ram -- Ram
CodePudding user response:
Maybe you want this:
var students = new List<Student>() {
new Student(){ Id = 1, Name="Bill"},
new Student(){ Id = 2, Name="Steve"},
new Student(){ Id = 3, Name="Ram"},
};
for (int i=0; i<students.Count(); i )
{
for (int x = 0; x < students.Count(); x )
{
if(students[i].Id != students[x].Id)
{
Console.WriteLine(students[i].Name " -- " students[x].Name);
}
}
}
then you'll get:
Bill -- Steve
Bill -- Ram
Steve -- Bill
Steve -- Ram
Ram -- Bill
Ram -- Steve
CodePudding user response:
You can try with C# Linq query in you first for
for (int i=0; i<students.Count; i )
{
IEnumerable<Student> compare = students.Where(s => s.Id != students[i].Id);
foreach(var c in compare)
{
Console.WriteLine(students[i].Name " -- " c.Name);
}
}
The IEnumerable class would have all the elements except the one who are you comparing
The Result will be
Bill -- Steve
Bill -- Ram
Steve -- Bill
Steve -- Ram
Ram -- Bill
Ram -- Steve