我在下面有一个示例列表。在我的主要内容中,我希望能够遍历queryResult并基于TotalNumberOfUsersInGrp值, 打印第一组中前5个用户的名称,然后打印另一组中的下5个用户的名称。
我无法继续,因为您只能将foreach与集合一起使用。
我该怎么办?
public class PlayerInformation
{
public string fullName { get; set; }
public string rating { get; set; }
}
class Program
{
static void Main(string[] args)
{
Int32 TotalNumberOfUsersInGrp = 5;
List<PlayerInformation> objGetPlayerInfor = RankPlayers();
var queryResult = objGetPlayerInfor.OrderByDescending(q => q.rating);
foreach (var item in queryResult)
{
foreach (var item2 in TotalNumberOfUsersInGrp)
{
//Todo...
//Print Group 1 as a header
//Print the fullName of the first 5 players under the title group1
//Next Print Group 2 as a header
//Print the 5 next names under the group 2 header.
}
}
}
public static List<PlayerInformation> RankPlayers()
{
List<PlayerInformation> objPlayers = new List<PlayerInformation>();
objPlayers.Add( new PlayerInformation{fullName = "Tola", rating = "1001"});
objPlayers.Add( new PlayerInformation{fullName = "David", rating = "1002"});
objPlayers.Add( new PlayerInformation{fullName = "Bayo", rating = "1003"});
objPlayers.Add( new PlayerInformation{fullName = "Sumbo", rating = "1005"});
objPlayers.Add( new PlayerInformation{fullName = "Demola", rating = "1008"});
objPlayers.Add( new PlayerInformation{fullName = "Patrick", rating = "2001"});
objPlayers.Add( new PlayerInformation{fullName = "Folusho", rating = "2004"});
objPlayers.Add( new PlayerInformation{fullName = "Olawale", rating = "2006"});
objPlayers.Add( new PlayerInformation{fullName = "Johnson", rating = "2008"});
objPlayers.Add( new PlayerInformation{fullName = "Ibrahim", rating = "1006"});
return objPlayers.ToList();
}
}
答案 0 :(得分:0)
你必须使用嵌套的foreach吗?第一个foreach输出所有玩家的结果(按比率下降)。如果你想一次打印5个玩家,你可以使用另一个玩家循环,或者在第一个foreach循环中打印5个玩家,如下所示:
int playerIndex=0;
int groupIndex=1;
foreach (var item in queryResult)
{
if((playerIndex%TotalNumberOfUsersInGrp)==0){
Console.WriteLine("group:" + groupIndex);
groupIndex++;
}
Console.WriteLine("player:" + item.fullName);
playerIndex++;
}