简体   繁体   中英

Spread items in multiple .NET collections

I am using VS 2015 to write a windows form application in C sharp. In this application, I have a string collection (List) that contain the names of multiple sport teams. I want to divide these sport teams into several groups. The number of groups that will be created are based on the number of sport teams in my string collection. For example, if I have less than 8 teams, I will spread the teams over two groups. My problem is that I cannot find a way to divide my items in my string collection over two new string collections. Underlying code shows that I can create on group and adding the string items but making two groups and spreading the items over these two new string collections is a problem for me. Feel free to give me some tips or help :

   if (i < 6)
   {
   /// Make one group and add the teams in this group
   List<string> groepa = new List<string>();
   foreach (var item in lstTeams)
   {
   groepa.Add(item);

   }

   }
   else if (i < 8)
   {
   /// Make two groups
   List<string> groepa = new List<string>();
   List<string> groepb = new List<string>();

You can divide the number of elements in the main list by two. Then take the first half and put them in a first list, the second half goes to the second list

int numElements = lstTeams / 2;
List<string> groepa = lstTeams.Take(numElements).ToList();
List<string> groepb = lstTeams.Skip(numElements).ToList();

This uses the IEnumerable extensions Take and Skip

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM