从字典中压缩所有列表

nap*_*ter 2 .net c# 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);
Run Code Online (Sandbox Code Playgroud)

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

one       1
two       2
three     3
four      4
Run Code Online (Sandbox Code Playgroud)

slo*_*oth 5

给定DictionaryListS:

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"}}
};
Run Code Online (Sandbox Code Playgroud)

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

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

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

var result = ZipIt(d.Values, xs => String.Join(", ", xs)).ToList();
Run Code Online (Sandbox Code Playgroud)

result 就是现在

在此输入图像描述

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