VB.NET(或 C#)从现有列表创建字典而不循环

发布于 2024-12-02 10:22:38 字数 382 浏览 1 评论 0原文

我不知道这是否可行,也许可以使用 Linq,但我有一个 List(Of MyType)

Public Class MyType

    Property key As Char
    Property description As String
End Class

并且我想创建一个 Dictionary(Of Char, MyType) 使用键字段作为字典键,使用 List 中的值作为字典值,类似于:

New Dictionary(Of Char, MyType)(??)

即使这是可行的,我猜它在内部也会循环遍历所有列表项?

I don't know if this is doable, maybe with Linq, but I have a List(Of MyType):

Public Class MyType

    Property key As Char
    Property description As String
End Class

And I want to create a Dictionary(Of Char, MyType) using the key field as the dictionary keys and the values in the List as the dictionary values, with something like:

New Dictionary(Of Char, MyType)(??)

Even if this is doable, internally it will loop through all the List items, I guess?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烛影斜 2024-12-09 10:22:38

此目的是通过 ToDictionary 扩展方法

Dim result = myList.ToDictionary(Function (x) x.key, Function (x) x.description)

即使这是可行的,我猜它在内部也会循环遍历所有列表项?

当然。事实上,不循环的实现可以想象的,但是会导致字典查找效率非常低(这样的实现会在现有列表上创建一个视图,而不是的副本)。这仅适用于非常非常小的词典(例如<10个项目)。

This purpose is fulfilled by the ToDictionary extension method:

Dim result = myList.ToDictionary(Function (x) x.key, Function (x) x.description)

Even if this is doable, internally it will loop through all the List items, I guess?

Of course. In fact, an implementation without looping is thinkable but would result in a very inefficient look-up for the dictionary (such an implementation would create a view on the existing list, instead of a copy). This is only a viable strategy for very small dictionaries (< 10 items, say).

诗笺 2024-12-09 10:22:38

在 C# 中,有 ToDictionary< /a>,但是它会循环:-)

您可以使用类似以下内容来调用它:myCollection.ToDictionary(p => p.key)。在 VB.NET 中,我认为语法是 myCollection.ToDictionary(Function(p) p.key)

In C# there is the ToDictionary<TKey, TSource>, but yes it will loop :-)

You would call it with something like: myCollection.ToDictionary(p => p.key). In VB.NET I think the syntax is myCollection.ToDictionary(Function(p) p.key)

月下客 2024-12-09 10:22:38

是的,它将循环遍历所有列表项。您可以做的另一件事是为您的列表创建一个 KeyedCollection

public class MyTypeCollection : KeyedCollection<char, MyType>
{
   protected override char GetKeyForItem(MyType item)
   {
      return item.key;
   }
}

但是不会帮助您添加项目。

Yes, it will loop through all the list items. Another thing you can do is create a KeyedCollection for your list:

public class MyTypeCollection : KeyedCollection<char, MyType>
{
   protected override char GetKeyForItem(MyType item)
   {
      return item.key;
   }
}

but that won't help you adding the items.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文