我有一本带有值列表的字典
列表是在运行时动态添加的。在 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
最佳答案
给定一个 List
的 Dictionary
:
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();
结果
现在
请注意,此方法允许您选择如何组合值;在我的示例中,我只是创建一个 ,
分隔的字符串。您也可以使用其他东西。
关于c# - 压缩字典中的所有列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14253810/