c# - 压缩字典中的所有列表

标签 c# .net zip

我有一本带有值列表的字典

列表是在运行时动态添加的。在 C# 中,如何从字典中压缩所有列表?

示例:

Dictionary<string, List<string>> MyDictionary = new Dictionary<string, List<string>>();

List<int> firstlist= new List<string>();

firstlist.Add("one");

firstlist.Add("two");

firstlist.Add("three");

firstlist.Add("four");

List<int> secondlist= new List<int>();

secondlist.Add(1);

secondlist.Add(2);

secondlist.Add(3);

secondlist.Add(4);

MyDictionary.Add("Words", firstlist);
MyDictionary.Add("Number", secondlist);

我想从 mydictionary 中压缩所有列表,因此结果是:

one       1
two       2
three     3
four      4

最佳答案

给定一个 ListDictionary:

var d = new Dictionary<string, List<string>>()
{
    {"first",  new List<string>() {"one", "two", "three"}},
    {"second", new List<string>() {"1",   "2",   "3"}}, 
    {"third",  new List<string>() {"A",   "B",   "C"}}
};

你可以使用这个通用方法:

IEnumerable<TResult> ZipIt<TSource, TResult>(IEnumerable<IEnumerable<TSource>> collection, 
                                            Func<IEnumerable<TSource>, TResult> resultSelector)
{
    var enumerators = collection.Select(c => c.GetEnumerator()).ToList();
    while (enumerators.All(e => e.MoveNext()))
    {
        yield return resultSelector(enumerators.Select(e => (TSource)e.Current).ToList());
    }
}

压缩此字典中的所有列表,例如如下所示:

var result = ZipIt(d.Values, xs => String.Join(", ", xs)).ToList();

结果现在

enter image description here

请注意,此方法允许您选择如何组合值;在我的示例中,我只是创建一个 , 分隔的字符串。您也可以使用其他东西。

关于c# - 压缩字典中的所有列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14253810/

相关文章:

c# - 使用 C# 在 WCF 中同时访问 PerSession 服务

c# - Excel 互操作 : Quitting the Excel application instance makes my tests fail?

bash - 需要在unix中压缩一定大小的单个文件并删除原始文件

linux - zip 放气 0% ?为什么不压缩?

c# - 使用 shell 时如何更改 iOS 中状态栏的颜色

c# - .net StopWatch 的计时不一致

c# - 参差不齐的任务数组 - 并发问题

c# - 在 C# 应用程序中使用 SQL 的最简单方法?

java - 写入 StringBuilder 时某些字符丢失

c# - 局部函数中声明的值类型变量是否是堆栈分配的?