C# - elegant way of partitioning a list?

前端 未结 11 688
情歌与酒
情歌与酒 2020-12-01 04:36

I\'d like to partition a list into a list of lists, by specifying the number of elements in each partition.

For instance, suppose I have the list {1, 2, ... 11}, and

11条回答
  •  离开以前
    2020-12-01 05:03

    You could use an extension method:

    public static IList> Partition(this IEnumerable input, Func partitionFunc)
    {
          Dictionary partitions = new Dictionary>();

      object currentKey = null;
      foreach (T item in input ?? Enumerable.Empty())
      {
          currentKey = partitionFunc(item);
    
          if (!partitions.ContainsKey(currentKey))
          {
              partitions[currentKey] = new HashSet();
          }
    
          partitions[currentKey].Add(item);
      }
    
      return partitions.Values.ToList();
    

    }

提交回复
热议问题