Can I select multiple objects in a Linq query

后端 未结 7 455
有刺的猬
有刺的猬 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:37

    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 MapCombine(this IEnumerable origList, params Func[] 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.

提交回复
热议问题