Can I select multiple objects in a Linq query

后端 未结 7 454
有刺的猬
有刺的猬 2021-02-02 06:48

Can I return more than one item in a select? For instance I have a List of Fixtures (think football (or soccer for the yanks) fixtures). Each fixture contains a home and away t

7条回答
  •  爱一瞬间的悲伤
    2021-02-02 07:22

    Taking a stab at this myself I came up with the same version as 'it depends'.

    Using query comprehension syntax:

    IEnumerable drew =
        from fixture in fixtures
        where fixture.Played && (fixture.HomeScore == fixture.AwayScore)
        from team in new[]{fixture.AwayTeam, fixture.HomeTeam}
        select team;
    

    Using lambda with extension methods:

    IEnumerable drew =
        fixtures.Where(f => f.Played && f.HomeScore == f.AwayScore)
        .SelectMany(f => new[]{f.HomeTeam, f.AwayTeam});
    

    Edit: I don't know if a team could have possibly played and drawn more than once in your database, but if that's possible, then you might want to make use of the Distinct query operator:

    IEnumerable drew =
        (from fixture in fixtures
         where fixture.Played && (fixture.HomeScore == fixture.AwayScore)
         from team in new[]{fixture.AwayTeam, fixture.HomeTeam}
         select team).Distinct();
    

    or:

    IEnumerable drew =
        fixtures.Where(f => f.Played && f.HomeScore == f.AwayScore)
        .SelectMany(f => new[]{f.HomeTeam, f.AwayTeam})
        .Distinct();
    

提交回复
热议问题