Linq筛选器集合内部集合

时间:2018-09-20 11:47:42

标签: c# asp.net linq

“我有一个包含这些详细信息的收藏夹

=IF(LOWER(B3)="yes", 1, 0)

我大约有16支球队,我需要选择比1998年更大的特定球队的数据。哪种方法最好?我尝试使用.Any,但它跳过并且仅采用季节过滤条件。有帮助吗?

4 个答案:

答案 0 :(得分:2)

根据我的理解,您需要具有符合条件的比赛的所有球队的名单,但具有基于此条件的比赛过滤器的名单。带有以下数据:

var allteams = new List<Team> {
    new Team
    {
        TeamName = "FooBar SO",
        TeamId = 1,
        Matchs = new List<Match>
        {
            new Match{ MatchName="ok" , Season=100 },
            new Match{ MatchName="notOk" , Season=10 }
        }
    },
    new Team
    {
        TeamName = "Other SO",
        TeamId = 2,
        Matchs = new List<Match>
        {
            new Match{ MatchName="nope" , Season=20 },
            new Match{ MatchName="notOk" , Season=10 }
        }
    }
};

1 /。至少有一场符合条件的所有球队。
 保留球队的比赛清单。

var teamsFilterOnSeason 
    = allteams.Where(t => t.Matchs.Any(m => m.Season >= 100));

结果:

 TeamName: FooBar SO,
 TeamId: 1,
 Matchs: 
 [
    { MatchName: ok, Season: 100 },
    { MatchName: notOk, Season: 10 }
 ]  

2 /。至少有一场符合条件的所有球队。
匹配列表将根据条件进行过滤。

var teamsWithSeasonFilter 
    = allteams
        .Where(t => t.Matchs.Any(m => m.Season >= 100))
        .Select(
            t => 
            new Team {
                TeamName = t.TeamName,
                TeamId = t.TeamId,
                Matchs= t.Matchs
                            .Where(m=> m.Season >= 100)
                            .ToList()
            }
        );

结果:

TeamName: FooBar SO,
TeamId: 1,
Matchs: 
[
    { MatchName: ok, Season: 100 }
]

答案 1 :(得分:1)

让我们说您有团队对象,您可以像下面那样使用Linq。...

 var result =teams.Where(x=> x.Match.Any(y=>y.Season>1998) && x.TeamId==123);

我认为您错过了比较运算符==

答案 2 :(得分:1)

public class Team
{
    public string TeamName { get; set; }
    public int TeamId { get; set; }
    public List<Match> Matches { get; set; }
}

public class Match
{
    public string MatchName { get; set; }
    public int Season { get; set; }
}

var teams = new List<Team> {
    new Team
    {
        TeamName = "Team 1",
        TeamId = 1,
        Matches = new List<Match>
        {
             new Match{ MatchName="Match 11" , Season=1 },
             new Match{ MatchName="Match 12" , Season=2 }
        }
    },
    new Team
    {
        TeamName = "Team 2",
        TeamId = 2,
        Matches = new List<Match>
        {
            new Match{ MatchName="Match 21" , Season=1 },
            new Match{ MatchName="Match 22" , Season=2 }
        }
    }
};

List<Match> team1seazon2 = teams.Where(t => t.TeamId == 1).SelectMany(t => t.Matches).Where(m => m.Season == 2).ToList();

答案 3 :(得分:0)

要获取任何赛季大于1998年的球队的球队数据:

var result = teams.Where(x => x.matches.Any(t => t.Season > 1998));