'compare items on a list except to yourself
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
Solution 1:[1]
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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nicolas Quintana |
| Solution 2 | Charly G |
