【问题标题】:Grouping and nesting list with LINQ使用 LINQ 分组和嵌套列表
【发布时间】:2016-11-30 10:56:51
【问题描述】:

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

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();

我得到的是一个运动列表,在每个运动节点中我得到一个锦标赛列表,但这就是它停止的地方,我似乎无法正确。

【问题讨论】:

  • 你想要输出什么?
  • APIExtendedFixtureModel 类的一个实例。我只是用类来说明结构

标签: c# linq group-by


【解决方案1】:

这将返回由锦标赛和固定装置填充的 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();

【讨论】:

    【解决方案2】:

    如果您想按多列分组,请创建一个匿名类型:

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

    如果需要,您也可以在其中添加更多列:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-08
      相关资源
      最近更新 更多