我想比较列表中的项目,但不希望将其与其自身进行比较。我怎么做?
我的代码:
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);
}
}
该代码返回...
Bill -- Bill
Bill -- Steve
Bill -- Ram
Steve -- Bill
Steve -- Steve
Steve -- Ram
Ram -- Bill
Ram -- Steve
Ram -- Ram
也许你想要这个:
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);
}
}
}
然后你会得到:
Bill -- Steve
Bill -- Ram
Steve -- Bill
Steve -- Ram
Ram -- Bill
Ram -- Steve
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)