Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing for loop C#

Tags:

c#

for-loop

I am using this loop to go through my database, and check if players Club field matches the clubAway variable. At if statement it "goes berzerk".

Baza = dataset

Players = table in database

Club = int field

int clubAway

I've checked the values with messagebox, and it says for example: Club = 1 and IDclub = 2.. But it enters the if statement anyway. I have exactly the same for loop, with difference that clubAway is clubHome and it works fine.

for (int o = 0; o <= 10; o++)
{
    for (int p = 1; p <= Baza.Players.Count; p++)
    {
        if (Baza.Players[p - 1 + o].Club == clubAway.IDclub)
        {//do something
        }
    }
}
like image 210
Dino Velić Avatar asked Nov 19 '25 04:11

Dino Velić


1 Answers

I am not clear on the purpose of o, but maybe this code will set you on a better path:

var players = Baza.Players.Where(player => player.Club == clubAway.IDclub).Take(11);

    foreach(var p in players){
        //do something with p
    }

UPDATE

In reading the comments below the original post, I deduce that you are simply trying to find the first instance in the set that matches the clubAway value. If that is correct, then one of these code snippets would be more appropriate (depending on your business rules):

var player = Baza.Players.FirstOrDefault(player => player.Club == clubAway.IDclub);

OR

var players = Baza.Players;
foreach(var _player in players){
     var player = _player.FirstOrDefault(p=> p.Club == clubAway.IDclub);
     //Now do something with player.
}

This will return the "player" entity. To use it you would do this (for example):

var playerTeamName = player.teamName;

Of course, I have no knowledge of your actual model, so your code will look different but will follow that pattern.

Good luck!

like image 178
Matt Cashatt Avatar answered Nov 21 '25 19:11

Matt Cashatt