0

我有两个班级名单球队和比赛

在我的团队类中,我有一个 int id 和字符串名称,而在比赛类中,我有 int team1Id 和 team2Id,我想知道是否有办法计算比赛列表中一个团队参加了多少场比赛。

喜欢

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

对不起,如果我没有很好地解释,英语不是我的第一语言。

编辑1:

这里是列表,public List teams= new List(); 公共列表匹配=新列表();Team 和 Match 是我的类,包含基本信息、id 和 name 用于 Team 和 id、team1 和 team2 用于 Match,我尝试使用 find 但它只返回一个结果

4

3 回答 3

1

这是 linq 示例:

List<Teamlist> item1 = new List<Teamlist>();
List<Matcheslist> item2 = new List<Matcheslist>();
var count = item1.Count(c => item2.Any(c2 => c2.Id2 == c.Id1));
于 2013-11-14T06:21:11.167 回答
1

鉴于这种设置:

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 } 
        }
    }
};

你可以这样计算它们:

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));
于 2013-11-14T06:21:22.313 回答
1

我想你想要这样的东西:

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++;
}

是您需要的“列表”关键字吗?或者您需要一个 LINQ 查询操作,例如:

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
于 2013-11-14T06:31:03.303 回答