如何将一个集合分成不同的桶#34;

时间:2017-06-07 11:21:38

标签: c#

我有一组C#对象。对于数据成员,每个对象都有一个作为guid的字符串,一个作为int的索引和一个作为文档名称的字符串。以下是典型的集合:

"guid1","c:\temp\doc1.docx",1
"guid1","c:\temp\doc2.docx",2
"guid1","c:\temp\doc3.docx",3
"guid1","c:\temp\doc4.docx",4
"guid2","c:\temp\doc5.docx",5
"guid1","c:\temp\doc6.docx",6
"guid1","c:\temp\doc7.docx",7


I need to end up breaking the collection into individual collections like this:

"guid1","c:\temp\doc1.docx",1
"guid1","c:\temp\doc2.docx",2
"guid1","c:\temp\doc3.docx",3
"guid1","c:\temp\doc4.docx",4


"guid2","c:\temp\doc5.docx",5


"guid1","c:\temp\doc6.docx",6
"guid1","c:\temp\doc7.docx",7

然后将这些单独的集合输入另一个功能进行处理。试图找出最佳方法。

2 个答案:

答案 0 :(得分:2)

尝试使用 Linq GroupBy

 IEnumerable<MyClass> source = ...;

 int group = 0;
 Guid key = new Guid(); 

 // Let's have an array of arrays (array of individual collections) as a result
 MyClass[][] buckets = source
   .GroupBy(item => {
      if (group == 0 || key != item.guid) {
        key = item.guid;
        group += 1; 
      } 

      return group; })
   .Select(chunk => chunk.ToArray()) 
   .ToArray(); 

答案 1 :(得分:1)

我用linq做了这个,没有外部变量

    var list = new []{
        new {Id = "guid1", Path = @"c:\temp\doc1.docx", Index = 1},
        new {Id = "guid1", Path = @"c:\temp\doc2.docx", Index = 2},
        new {Id = "guid1", Path = @"c:\temp\doc3.docx", Index = 3},
        new {Id = "guid1", Path = @"c:\temp\doc4.docx", Index = 4},
        new {Id = "guid2", Path = @"c:\temp\doc5.docx", Index = 5},
        new {Id = "guid1", Path = @"c:\temp\doc6.docx", Index = 6},
        new {Id = "guid1", Path = @"c:\temp\doc7.docx", Index = 7}
    };


    var batchSize = 3;

    var batched = list.GroupBy(x => x.Id)
                    .Select(x => x.GroupBy(p => p.Index/batchSize)
                                    .ToArray());

    string json = JsonConvert.SerializeObject(batched);

    Console.WriteLine(json);

json序列化仅用于在屏幕上打印输出,即:

[
   [
      [
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc1.docx",
            "Index":1
         },
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc2.docx",
            "Index":2
         }
      ],
      [
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc3.docx",
            "Index":3
         },
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc4.docx",
            "Index":4
         }
      ],
      [
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc6.docx",
            "Index":6
         },
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc7.docx",
            "Index":7
         }
      ]
   ],
   [
      [
         {
            "Id":"guid2",
            "Path":"c:\\temp\\doc5.docx",
            "Index":5
         }
      ]
   ]
]