比较结构C#中的两个变量
Comparing two variable in a structure C#
我想做的是比较结构中的两个相同变量。
例如我有这样的结构:
struct player
{
public string name;
public int number;
}
static player[] players = new player[3];
我想做的是比较数字,这样如果两个玩家的数字相同,就会发生一些事情。
这是我尝试过的方法,但是它总是会说两个数字相同,因为它会比较两个相同的数字
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
if (players[i].number == players[j].number)
{
Console.WriteLine("Same");
Console.ReadLine();
}
else
{
Console.WriteLine("Not");
Console.ReadLine();
}
}
希望你明白我的意思。
任何帮助将非常感激!
谢谢
问题出在您的循环变量 i
和 j
中,它们都从索引零开始。然后您将元素零与元素零进行比较,因此条件为真。
更新这一行:
for (int j = 0; j < length; j++)
对此:
for (int j = i + 1; j < length; j++)
编辑
更准确地说。 条件不仅对第一个元素求值为真,而且对每个元素求值为真,当 i
和 j
是相同的。此解决方案禁止两个控制变量在任何迭代中具有相同的值。
很简单,只需添加一个检查以确保您比较的不是同一个索引,因为这是同一个对象:
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
if (i == j) continue;
if (players[i].number == players[j].number)
{
Console.WriteLine("Same");
Console.ReadLine();
}
else
{
Console.WriteLine("Not");
Console.ReadLine();
}
}
使用 Class,并使用 Linq:
public class Player
{
public string Name { get; set; }
public int Number { get; set; }
}
然后在其他class有这个方法来交叉检查
private void Match()
{
var players = new Player[3].ToList();
foreach (var found in players.ToList().Select(player => players.FirstOrDefault(p => p.Number == player.Number)))
{
if (found != null)
{
Console.WriteLine("Same");
Console.ReadLine();
}
else
{
Console.WriteLine("Not");
Console.ReadLine();
}
}
}
我想做的是比较结构中的两个相同变量。 例如我有这样的结构:
struct player
{
public string name;
public int number;
}
static player[] players = new player[3];
我想做的是比较数字,这样如果两个玩家的数字相同,就会发生一些事情。
这是我尝试过的方法,但是它总是会说两个数字相同,因为它会比较两个相同的数字
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
if (players[i].number == players[j].number)
{
Console.WriteLine("Same");
Console.ReadLine();
}
else
{
Console.WriteLine("Not");
Console.ReadLine();
}
}
希望你明白我的意思。 任何帮助将非常感激! 谢谢
问题出在您的循环变量 i
和 j
中,它们都从索引零开始。然后您将元素零与元素零进行比较,因此条件为真。
更新这一行:
for (int j = 0; j < length; j++)
对此:
for (int j = i + 1; j < length; j++)
编辑
更准确地说。 条件不仅对第一个元素求值为真,而且对每个元素求值为真,当 i
和 j
是相同的。此解决方案禁止两个控制变量在任何迭代中具有相同的值。
很简单,只需添加一个检查以确保您比较的不是同一个索引,因为这是同一个对象:
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
if (i == j) continue;
if (players[i].number == players[j].number)
{
Console.WriteLine("Same");
Console.ReadLine();
}
else
{
Console.WriteLine("Not");
Console.ReadLine();
}
}
使用 Class,并使用 Linq:
public class Player
{
public string Name { get; set; }
public int Number { get; set; }
}
然后在其他class有这个方法来交叉检查
private void Match()
{
var players = new Player[3].ToList();
foreach (var found in players.ToList().Select(player => players.FirstOrDefault(p => p.Number == player.Number)))
{
if (found != null)
{
Console.WriteLine("Same");
Console.ReadLine();
}
else
{
Console.WriteLine("Not");
Console.ReadLine();
}
}
}