Skip to main content
 首页 » 编程设计

c#之如何在 C# 中通过 Linq 分块字典

2024年02月23日16www_RR

我有一本字典,我需要将其分块到一个组中的 9 个字典项的列表中,并将其他 9 个项分到下一个组中,依此类推...,

试过这段代码,

    public static List<List<DictionaryEntry>> ChunkDict(Dictionary<string,string> theList, int chunkSize)  
    {  
        List<List<DictionaryEntry>> result = theList.Select((x, i) =>  
            new { data = x, indexgroup = i / chunkSize }) 
            .GroupBy(x => x.indexgroup, x => x.data) 
            .Select(g => new List<DictionaryEntry>(g)).ToList();  
        return result;  
    }  

但它没有编译,出现错误:Error 398 The best overloaded method match for 'System.Collections.Generic.List.List(System.Collections.Generic.IEnumerable)' has some invalid arguments

我该怎么做?

请您参考如下方法:

我不久前写了这篇文章来做到这一点:

public static class EnumerableExtensions 
{ 
    public static IEnumerable<IEnumerable<TElement>> Partition<TElement>(this IEnumerable<TElement> @this, int partitionSize) 
    { 
        if (@this == null) throw new ArgumentNullException("this"); 
 
        return new PartitionedEnumerable<TElement>(@this, partitionSize); 
    } 
 
    private sealed class PartitionedEnumerable<TElement> : IEnumerable<IEnumerable<TElement>> 
    { 
        #region Public 
 
        public PartitionedEnumerable(IEnumerable<TElement> elements, int partitionSize) 
        { 
            this.elements = elements; 
            this.partitionSize = partitionSize; 
        } 
 
        IEnumerator IEnumerable.GetEnumerator() 
        { 
            return GetEnumerator(); 
        } 
 
        public IEnumerator<IEnumerable<TElement>> GetEnumerator() 
        { 
            IEnumerator<TElement> elementEnumerator = this.elements.GetEnumerator(); 
 
            var partition = new List<TElement>(); 
            while (elementEnumerator.MoveNext()) 
            { 
                partition.Add(elementEnumerator.Current); 
 
                if (partition.Count == partitionSize) 
                { 
                    yield return partition; 
                    partition = new List<TElement>(); 
                } 
            } 
 
            if (partition.Count > 0) yield return partition; 
        } 
 
        #endregion 
 
        #region Private 
 
        private readonly IEnumerable<TElement> elements; 
        private readonly int partitionSize; 
 
        #endregion 
    } 
} 

例子:

IDictionary<string, string> dictionary = ...; 
foreach (IEnumerable<KeyValuePair<string, string>> triplet in dictionary.Partition(3)) 
{ 
    ... // use the triplet 
} 

如果您希望它们作为字典返回:

IEnumerable<Dictionary<string, string>> partitioned = dictionary.Partition(3) 
                                                                .Select(_ => _.ToDictionary());