创建一个将键作为列表(字符串)的字典

需要创建一个字典,其中键是list(Of String)或字符串数组


我发现这个链接C#列表作为字典键


但我需要帮助来了解如何使用list(的字符串)来做到这一点


Class test

    Sub TryTest()

        myDict.Add(New List(Of String) From {"Huey", "Dewey"}, actions.Sleeping)

        myDict.Add(New List(Of String) From {"Dewey", "Louie"}, actions.Playing)


        Dim newList As New List(Of String) From {"Dewey", "Louie"}

        If myDict.ContainsKey(newList) Then

            MsgBox("myDict contains the list of String, as Key Value")

        Else

            MsgBox("myDict don't contains the list of String, as Key Value")

        End If

    End Sub


    Dim myDict As New Dictionary(Of List(Of String), actions)


End Class


Enum actions

    Sleeping

    Eating

    Studying

    Playing

End Enum

我期望包含键的字典输出。


P.S. 由于 c# 接近 vb.net,并且网络上有很多 c#/vb.net 翻译人员可以轻松翻译,拜托,也非常感谢 c# 的帮助。


紫衣仙女
浏览 72回答 2
2回答

互换的青春

跟using System.Collections;using System.Collections.Generic;你可以创建一个类,如sealed class ListComparer : EqualityComparer<List<string>>{&nbsp; public override bool Equals(List<string> x, List<string> y)&nbsp; &nbsp; => StructuralComparisons.StructuralEqualityComparer.Equals(x, y);&nbsp; public override int GetHashCode(List<string> x)&nbsp; &nbsp; => StructuralComparisons.StructuralEqualityComparer.GetHashCode(x);}然后将其用作Dictionary<,>myDict = new Dictionary<List<string>, Actions>(new ListComparer());该类也可以是泛型的。ListComparersealed class ListComparer<T> : EqualityComparer<List<T>>编辑:在评论之后,我意识到这不起作用(我曾经想过)!它适用于和诸如.所以上面的类需要改成:StructuralEqualityComparerList<string>string[]Tuple<string, string, ...>sealed class ListComparer : EqualityComparer<List<string>>{&nbsp; public override bool Equals(List<string> x, List<string> y)&nbsp; &nbsp; => StructuralComparisons.StructuralEqualityComparer.Equals(x?.ToArray(), y?.ToArray());&nbsp; public override int GetHashCode(List<string> x)&nbsp; &nbsp; => StructuralComparisons.StructuralEqualityComparer.GetHashCode(x?.ToArray());}我最初的尝试是错误的!

精慕HU

问题是你比较2个对象。您需要比较其中的值。我不知道我的代码 vb.net 是c#(LINQ)。像这样做。var myDic = new Dictionary<List<string>, Actions>();myDic.Add(new List<string>() { "Huey", "Dewey" }, Actions.Sleeping);myDic.Add(new List<string>() { "Dewey", "Louie" }, Actions.Playing);var newList = new List<string>() { "Dewey", "Louie" };if (myDic.Keys.Any(key =>{&nbsp; &nbsp; if (key.Count != newList.Count) return false;&nbsp; &nbsp; var same = true;&nbsp; &nbsp; for (int i = 0; i < newList.Count; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (key[i] != newList[i]) same = false;&nbsp; &nbsp; }&nbsp; &nbsp; return same;}))&nbsp; &nbsp; MsgBox("myDict contains the list of String, as Key Value");else&nbsp; &nbsp; MsgBox("myDict don't contains the list of String, as Key Value")
打开App,查看更多内容
随时随地看视频慕课网APP