我在VB中分组了字符集合。净
比如
HashTable(
"A", List(OF Char) [ A,A,A,A,A,A,A,A],
"B", List(OF Char) [ B,B,B,B,B],
"C", List(OF Char) [ C,C,C]
)
我想分割集合与Linq成2+1"页"(新集合与3嵌套集合),每个包含一个相等的数字每个字符
例如,从上面的哈希表中,结果应该是List(
list(of char) [ A,A,A,A,B,B,C ]
list(of char) [ A,A,A,A,B,B,C ]
list(of char) [ B,C ] // LAST PAGE CONTAINS
)
对不起我的英语…谢谢。
Dim input As New Dictionary(of Char, Char())
input.Add("A"c, {"A"c, "A"c, "A"c, "A"c, "A"c, "A"c, "A"c, "A"c})
input.Add("B"c, {"B"c, "B"c, "B"c, "B"c, "B"c})
input.Add("C"c, {"C"c, "C"c, "C"c})
Dim output As New List(of List(Of Char))
output.Add(input.SelectMany(Function(c) Enumerable.Repeat(c.Key, c.Value.Count 2)).ToList())
output.Add(output(0).ToList())
output.Add(input.SelectMany(Function(c) Enumerable.Repeat(c.Key, c.Value.Count Mod 2)).ToList())
这至少接近你想要的结果(结果列表包含3个(6/5/5)个字符的列表):
Dim dict = New Dictionary(Of String, List(Of Char)) From {
{"A", New List(Of Char) From {"A"c, "A"c, "A"c, "A"c, "A"c, "A"c, "A"c, "A"c}},
{"B", New List(Of Char) From {"B"c, "B"c, "B"c, "B"c, "B"c}},
{"C", New List(Of Char) From {"C"c, "C"c, "C"c}}
}
Dim pageCount = 3
Dim allChars = dict.Values.SelectMany(Function(chr) chr)
Dim result As List(Of List(Of Char)) = allChars.
Select(Function(chr, i) New With {.Char = chr, .Index = i}).
GroupBy(Function(x) x.Index Mod pageCount).
Select(Function(g) g.Select(Function(x) x.Char).ToList()).
ToList()
通过使用Enumerable.GroupBy
和Mod
操作符,将字典的Values
属性中的所有字符拆分为所需的页数(在您的示例中为3)。
嘿-你可以用LINQ做什么乱七八糟的事情…这里有一个与Tim的略有不同的理解
(对不起,我的VB真的很生疏,但这应该或多或少是可翻译的)
var table = new Dictionary<char,List<char>>()
{
{'A', new List<char>() {'A','A','A','A','A','A','A','A'}},
{'B', new List<char>() {'B','B','B','B','B'}},
{'C', new List<char>() {'C','C','C'}},
};
var result = table
.Select(kvp => new [] {
new string(kvp.Key, kvp.Value.Count / 2),
new string(kvp.Key, kvp.Value.Count / 2),
new string(kvp.Key, kvp.Value.Count % 2 == 0 ? 0 : 1) })
.Aggregate((acc, entry) => new [] {
acc[0] + entry[0],
acc[1] + entry[1],
acc[2] + entry[2]})
.Select(s => s.ToCharArray().ToList())
.ToList();