2013-07-16 43 views
3

我有一个包含对象(俱乐部)列表的对象(区域)列表,我想根据俱乐部的总数将其分成四个部分。将列表的列表等分为C#

可以说我有一个包含不同数量的俱乐部的x区域的列表。 如果俱乐部的总数是40,那么每组俱乐部应该有大约10个俱乐部。

public class Club 
{ 
    public string Name { get; set; } 
    public int ID { get; set; } 
} 

public class Region 
{ 
    public string Name { get; set; } 
    public List<Club> Club { get; set; } 
} 
+0

你关心的秩序?这可以通过一些扩展方法很容易地完成,但类名称“Region”意味着您可能希望它在空间上进行分组,这会使问题变得非常不同。 –

+0

[LINQ分区列表成8个成员列表]的可能副本(http://stackoverflow.com/questions/3773403/linq-partition-list-into-lists-of-8-members) – nawfal

回答

5

您可以使用组(不保留俱乐部的顺序)

List<IEnumerable<Club>> groups = region.Club.Select((c,i) => new {c,i}) 
              .GroupBy(x => x.i % 4) 
              .Select(g => g.Select(x => x.c)) 
              .ToList(); 

或者MoreLINQ批次(保留俱乐部的顺序排列):

int batchSize = region.Club.Count/4 + 1; 
var groups = region.Club.Batch(batchSize); 
+1

+1 for MoreLINQ。 – Nick

1

我使用自定义的扩展方法支持部分索引。基本上它在lazyberezovsky的答案中做了同样的事情。

public static class PartitionExtensions 
{ 
    public static IEnumerable<IPartition<T>> ToPartition<T>(this IEnumerable<T> source, int partitionCount) 
    { 
     if (source == null) 
     { 
      throw new NullReferenceException("source"); 
     } 

     return source.Select((item, index) => new { Value = item, Index = index }) 
        .GroupBy(item => item.Index % partitionCount) 
        .Select(group => new Partition<T>(group.Key, group.Select(item => item.Value))); 
    } 
} 

public interface IPartition<out T> : IEnumerable<T> 
{ 
    int Index { get; } 
} 

public class Partition<T> : IPartition<T> 
{ 
    private readonly IEnumerable<T> _values; 

    public Partition(int index, IEnumerable<T> values) 
    { 
     Index = index; 
     _values = values; 
    } 

    public int Index { get; private set; } 

    public IEnumerator<T> GetEnumerator() 
    { 
     return _values.GetEnumerator(); 
    } 

    IEnumerator IEnumerable.GetEnumerator() 
    { 
     return GetEnumerator(); 
    } 
} 

您可以使用它像这样:

var partitions = regionList.SelectMany(item => item.Club).ToPartition(4); 
+0

这不适用于一个地区的所有俱乐部吗? 我有一个地区名单,我需要根据他们内部俱乐部的数量分为四个地区。 –

+0

@JohanKetels是的,我现在更新它。 –

0
public static class BatchingExtensions 
{ 
    public static IEnumerable<List<T>> InBatches<T>(this IEnumerable<T> items, int length) 
    { 
     var list = new List<T>(length); 
     foreach (var item in items) 
     { 
      list.Add(item); 
      if (list.Count == length) 
      { 
       yield return list; 
       list = new List<T>(length); 
      } 
     } 
     if (list.Any()) 
      yield return list; 
    } 
} 
相关问题