使用LINQ分组和嵌套列表

时间:2016-11-30 10:56:52

标签: c# linq group-by

我有一个由以下夹具类的对象组成的列表:

public class APIFixtureModel
{
    public string HomeTeamName { get; set; }
    public string AwayTeamName { get; set; }
    public string TournamentName { get; set; }
    public string SportType { get; set; }
    public DateTime FixtureDateTime { get; set; }
}

所以在我目前的设置中,我得到了一个灯具列表,这很不错,但我需要一个结构,其中列表按运动类型分组,然后按锦标赛分组。举例说明:

public class APIExtendedFixtureModel
{
    private List<Sport> lstSports;

    class Sport
    {
        public string SportType { get; set; }
        public List<Tournament> lstTournaments;
    }

    class Tournament
    {
        public string TournamentName { get; set; }
        public List<Fixture> lstFixtures;
    }

    class Fixture
    {
        public string HomeTeamName { get; set; }
        public string AwayTeamName { get; set; }
        public DateTime FixtureDateTime { get; set; }
    }
}

我尝试了以下内容:

 var testgroup = lstFixtures.GroupBy(f => f.SportType,
                                     f => f.TournamentName,
                                        (key,g) => new
                                        {
                                            Sport = key,
                                            Tournament = g.ToList()
                                        }).ToList();

我得到的是运动列表,在每个运动节点内我都会获得一个列表锦标赛,但是它停止了,我似乎无法做到正确。

2 个答案:

答案 0 :(得分:2)

这将返回填充了锦标赛和赛程的Sport对象列表:

List<Sport> sports = 
    fixtureList.GroupBy(f => f.SportType).Select(sGroup => new Sport 
        { 
            SportType = sGroup.Key,
            lstTournaments = sGroup.GroupBy(f => f.TournamentName).Select(tGroup => new Tournament 
                {               
                    TournamentName = tGroup.Key,
                    lstFixtures = tGroup.Select(f => new Fixture 
                        {
                            HomeTeamName = f.HomeTeamName,
                            AwayTeamName = f.AwayTeamName,
                            FixtureDateTime = f.FixtureDateTime,
                        }).ToList(),
                }).ToList()
        }).ToList();

答案 1 :(得分:-1)

如果要按多列分组,请创建匿名类型:

var testgroup = lstFixtures.GroupBy(f => new { f.SportType, f.TournamentName },
                                        (key,g) => new
                                        {
                                            Sport = key.SportType,
                                            Tournament = key.TournamentName,
                                            Result = g.ToList()
                                        });

如果您愿意,也可以向其添加更多列:)