gpt4 book ai didi

c# - 如何将一个集合分成不同的 "buckets"

转载 作者:行者123 更新时间:2023-11-30 21:40:39 26 4
gpt4 key购买 nike

我有一组 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

然后,这些单独的集合将被送入另一个函数进行处理。试图找出执行此操作的最佳方法。

最佳答案

尝试使用 LinqGroupBy:

 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();

关于c# - 如何将一个集合分成不同的 "buckets",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44411263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com