合并具有相似键和concat值的两个列表或单个列表

时间:2018-01-26 06:36:38

标签: vb.net

我有两个字符串列表可能没有相同的键和值 list1的

(0) = {[Str1, J44]}
(1) = {[Str2, J45]}
(2) = {[Str3, J46]}

list2中

(0) = {[Str1, J47]}
(1) = {[Str2, J48]}
(2) = {[Str3, J49]}
(3) = {[Str4, J50]}

我想将这些连接或合并为 mergedList

(0) = {[Str1, =J44+J47]}
(1) = {[Str2, =J45+J48]}
(2) = {[Str3, =J46+J49]}
(3) = {[Str4, =J50]}

第二个选项     我可以将所有这些作为List1列入单个列表中     (0)= {[Str1,J44]}     (1)= {[Str2,J45]}     (2)= {[Str3,J46]}     (3)= {[Str1,J47]}     (4)= {[Str2,J48]}     (5)= {[Str3,J49]}     (6)= {[Str4,J50]}

我需要与上面相同的结果。为此我已经做了第二个选项

Dim MergePavStr = (From kvps In List1 Group kvps By kvps.Key Into Group Select New KeyValuePair(Of String, String)(Key, Group.Concat(Function(kvp) kvp.Value))).ToList()

但我找不到合适的方法。

UPdate Solved 我通过执行以下代码实现了它。希望这也是解决方案,因为我对vb.net很新。

Dim MergePavStr = (From kvps In List1 Group kvps By kvps.Key Into Group Select New KeyValuePair(Of String, String)(Key, String.Join("+", Group.Select(Function(p) p.Value).ToArray()))).ToList()

2 个答案:

答案 0 :(得分:0)

我不清楚您使用的是哪种数据结构。你有没有考虑过这么简单的方法?

Module Module1

    Sub MergeInto(dest As Dictionary(Of String, List(Of String)), src As Dictionary(Of String, String))
        For Each kvp In src
            If dest.ContainsKey(kvp.Key) Then
                dest(kvp.Key).Add(kvp.Value)
            Else
                dest.Add(kvp.Key, New List(Of String) From {kvp.Value})
            End If
        Next
    End Sub

    Sub Main()
        Dim x As New Dictionary(Of String, String) From {{"Str1", "J44"}, {"Str2", "J45"}, {"Str3", "J46"}}
        Dim y As New Dictionary(Of String, String) From {{"Str1", "J47"}, {"Str2", "J48"}, {"Str3", "J49"}, {"Str4", "J50"}}
        Dim z As New Dictionary(Of String, List(Of String))

        MergeInto(z, x)
        MergeInto(z, y)

        Dim i = 0
        For Each kvp In z
            Console.WriteLine($"({i}) = {{[{kvp.Key}, ={String.Join("+", kvp.Value)}]}}")
            i += 1
        Next

        Console.ReadLine()

    End Sub

End Module

输出:

  

(0)= {[Str1,= J44 + J47]}
  (1)= {[Str2,= J45 + J48]}
  (2)= {[Str3,= J46 + J49]}
  (3)= {[Str4,= J50]}

作为一种扩展方法,它当然会更整洁,它需要一个更好的名称,这是留给读者的练习。

答案 1 :(得分:0)

您可以在分组之前将键值对列表(或词典)与 $(function () { // boostrap 4 load modal example from docs $('#modal-container').on('show.bs.modal', function (event) { var button = $(event.relatedTarget); // Button that triggered the modal var url = button.attr("href"); var modal = $(this); // note that this will replace the content of modal-content everytime the modal is opened modal.find('.modal-content').load(url); }); $('#modal-container').on('hidden.bs.modal', function () { // remove the bs.modal data attribute from it $(this).removeData('bs.modal'); // and empty the modal-content element $('#modal-container .modal-content').empty(); }); }); 结合使用:

.Concat