If you are faimiar with Scala, you must have heard or used the function flatMap which is a very useful function that enable you to flat a collection.
There is no such flatMap or Map method as in Scala, however, the C# linq has provide you with the necessary tools to allow you to do the flat map.
this has been discussed in this post "USE LINQ'S SELECTMANY METHOD TO "FLATTEN" COLLECTIONS", it has been discussed.
Below I will save the droll and let's see the code.
class League
{
public string Name { get; set; }
public Team[] Teams { get; set; }
}
class Team
{
public string Name { get; set; }
public Player[] Players { get; set; }
public int NumberOfWins { get; set; }
public string HomeState { get; set; }
}
class Player
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
var leagues = new List<League>
{
new League {
Name = "AFC-West",
Teams = new []{
new Team {
Name = "Chargers",
NumberOfWins = 3,
HomeState = "CA",
Players = new [] {
new Player { Name = "Rivers", Age = 30 },
new Player { Name = "Tomlinson" , Age = 23},
new Player { Name = "Gates" , Age = 18},
}
},
new Team {
Name = "Croncos",
NumberOfWins = 2,
HomeState = "LOS",
Players = new [] {
new Player { Name = "Culter", Age = 23 },
new Player { Name = "Bailey", Age = 28 },
new Player { Name = "Marshal", Age = 30 },
}
},
}
},
new League {
Name = "AFC-South",
Teams = new [] {
new Team {
NumberOfWins = 1,
Name = "Colts",
HomeState = "NY",
Players = new [] {
new Player { Name = "Manning", Age = 31 },
new Player { Name = "Bailey" , Age = 19},
new Player { Name = "Vinatieri" , Age = 26},
}
},
}
},
};
var allTeams = from t in leagues.
SelectMany(l => l.Teams)
select t;
var allPlayers = from p in leagues
.SelectMany(l => l.Teams)
.SelectMany(t => t.Players)
select p;
var onlyYoungPlayers = from p in leagues
.SelectMany(l => l.Teams)
.SelectMany(t => t.Players)
where p.Age < 25
select p;
var players = leagues.SelectMany(l => l.Teams)
.Where(t => t.NumberOfWins > 2)
.Where(p => p.HomeState == "CA")
.Select(p => p);
var teamsAndTheirLeagues = from helper in leagues
.SelectMany(l => l.Teams, (league, team) => new { league, team })
where helper.team.Players.Length > 2
&& helper.league.Teams.Length < 10
select new { LeagueID = helper.league.Name, Team = helper.team };
}
}
本文通过具体的 C# 代码示例介绍了如何使用 LINQ 的 SelectMany 方法来扁平化集合,展示了从联赛到球队再到球员的数据遍历过程,并提供了过滤年轻球员等实用场景。
2968

被折叠的 条评论
为什么被折叠?



