Alex Rivera | Logout

Can I select multiple objects in a Linq query

Asked 2009-02-06T15:45:21.837
41

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 team and a home and away score. I want to get all the teams that drew. I want to use something like

IEnumerable<Team> drew = from fixture in fixtures
                         where fixture.Played && (fixture.HomeScore == fixture.AwayScore)
                         select fixture.HomeTeam && fixture.AwayTeam;

I know this syntax is incorrect, what I don't know is if it's possible to do this. Would I need two queries and then concatenate them?

Edit: this is really a learning thing so it's not critical to achieve this in any particular way. Basically, at this stage all i want is a list of teams that have drawn. An example usage might be that for a given list of fixtures i can find all of the drawn teams so that i could update their standings in a table by 1 point (3 for a win, 0 for a loss).

Edit
Report

2 Answers

5

Edit: Sorry, misunderstood your original question, so rewrote answer.

You could use the "SelectMany" operator to do what you want:

IEnumerable<Team> drew =
           (from fixture in fixtures
            where fixture.Played && (fixture.HomeScore == fixture.AwayScore)
                  select new List<Team>()
                             { HomeTeam = fixture.HomeTeam,
                               AwayTeam = fixture.AwayTeam
                             }).SelectMany(team => team);

This will return a flattened list of teams that drew.

answered 2009-02-06T15:51:49.220
1

I came up against this very issue, and couldn't find what I wanted so I wrote a small extension method which did what I wanted.

public static IEnumerable<R> MapCombine<M, R>(this IEnumerable<M> origList, params Func<M, R>[] maps)
{
    foreach (var item in origList)
    foreach (var map in maps)
    {
        yield return map(item);
    }
}

Following the problem in the question, you would then do something like this

var drew = fixtures.Where(fixture => fixture.Played && 
                        (fixture.HomeScore == fixture.AwayScore))
                    .MapCombine(f => f.HomeTeam, f => f.AwayTeam);

Interestingly intellisense isn't exactly happy about this, you don't get the lamdba expression in the top of the drop down, however after the '=>' its quite happy. But the main thing is the compiler is happy.

answered 2011-10-25T16:05:08.847

Your Answer