Raphael Jayme
Raphael Jayme

Reputation: 53

Count list with parameters?

I have two class lists teams, and matches

In my teams class I have a int id and string name and on the matches class I have int team1Id and team2Id, I want to know if there's a way to count on matches list how many matches a team participate..

Like

if(teamlist.id == matcheslist.team1 || teamlist.id == matcheslist.team2) count++;

Sorry if I didn't explain very well, english isn't my first language.

EDIT1:

Here the lists, public List teams= new List(); public List matches = new List(); Team and Match are my classes, with basic information, id and name for Team and id, team1 and team2 for Match, I tried to use find but it only return one result

Upvotes: 0

Views: 1347

Answers (3)

Sheldon
Sheldon

Reputation: 97

I think you want something like:

List<teamlist> list = new List<teamlist>();
int count = 0;
list.Add(team1);
list.Add(team2);
...
foreach(teamlist tl in list)
{
    if(teamlist.id == matcheslist.team1 || teamlist.id == matcheslist.team2) count++;
}

Is that "List" keyword you need ? Or you need a LINQ query operation like:

using System.Linq;
...
List<int> list = new List<int>();
list.AddRange(new []{1,2,3,4,5,6});
int count = list.Count(n => n > 2); // 4

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65077

Given this sort of setup:

class Team {
    public int TeamId { get; set; }
}

class Match {
    public Team[] Teams { get; set; }
}

var matches = new List<Match>() { 
    new Match() {
        Teams = new Team[] {
            new Team() { TeamId = 1 },
            new Team() { TeamId = 2 } 
        }
    },
    new Match() {
        Teams = new Team[] {
            new Team() { TeamId = 1 },
            new Team() { TeamId = 15 } 
        }
    }
};

You can count them like so:

var teamOneGameCount = matches.Count(match => match.Teams.Any(team => team.TeamId == 1));
var teamTwoGameCount = matches.Count(match => match.Teams.Any(team => team.TeamId == 2));
var teamFifteenGameCount = matches.Count(match => match.Teams.Any(team => team.TeamId == 15));

Upvotes: 1

Kain
Kain

Reputation: 273

here is linq example:

List<Teamlist> item1 = new List<Teamlist>();
List<Matcheslist> item2 = new List<Matcheslist>();
var count = item1.Count(c => item2.Any(c2 => c2.Id2 == c.Id1));

Upvotes: 1

Related Questions