简体   繁体   English

将项目分散到多个.NET集合中

[英]Spread items in multiple .NET collections

I am using VS 2015 to write a windows form application in C sharp. 我正在使用VS 2015在C Sharp中编写Windows窗体应用程序。 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. 例如,如果我的团队少于8个,则将团队分为两组。 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. 您可以将主列表中的元素数除以2。 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 这使用IEnumerable扩展Take and Skip

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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