gpt4 book ai didi

c# - Convert To Dictionary 需要有一个 Node 作为键

转载 作者:太空宇宙 更新时间:2023-11-03 13:44:49 27 4
gpt4 key购买 nike

public Dictionary<Node<T>, IList<Node<T>>> FlattenedMap { get; private set; }
private List<Node<T>> _dependencies; (note: these T instances have a NodeId and related ParentNodeId properties in it to work with)

.... 更多代码,然后:

public void CreateFlattenedMap()
{
var groups = _dependencies.GroupBy(d => d.ParentId); // attempt to groupy the list by ParentNodeId

var dictionary = parentGroups.ToDictionary(d => d.Key, d => d.ToList()); // attempt to flatten out each pair of parent Node<T> instances with their corresponding Parent Node<T>.Children list

FlattenedMap = dictionary;
}

我正在尝试将组转换为字典,但我不希望键为 ID。因为我的 FlattenedMap 有一个 Node 键所以不知道如何做 ToDictionary并让键成为 d,而不是 d。Key 基本上是为了让这个任务愉快。

所以问题就在这里:FlattenedMap = dictionary;因为字典最终是 <int, List<Node<T>>>而不是我想要的 <Node<T>, List<Node<T>>以满足我希望通过属性作为最终结果形成字典的方式。

更新

所以我尝试做但不适用于下面的伪代码是因为 d 是 T 类型并且字典确实需要 Node 作为键,而不是 d.Key(不是 T.Key)我试图做这样的事情:

var dictionary = parentGroups.ToDictionary(d => new Node<T>(d), d => d.ToList());

实际上现在我想起来了,List 不需要是 List<d>IList<d>但是List<Node<T>(d)><Node<d>> 的列表(记住 T 是 d 的一个实例,Node 期望任何已经实现了 d 肯定具有的 INode 的实例)。

ToDictionary 确实创建了这个:<d.Key, List<d>>所以你最终得到 (<int, List<d>)这不是我最终字典所期望的。

我需要以某种方式获取 d 并将其在 ToDictionary 中动态转换为 Node,所以我最终得到了 Dictionary>...希望我说的是对的,但您可以了解我正在尝试的内容满怀希望地说。

更新

所以尝试了一些不同的方法,我首先将我的 _dependencies 转换为所有 Node 实例,以尝试使其更易于使用或使其在我的 CreateFlattenedMap() 中工作

现在播种,在我循环原始依赖列表并将它们中的每一个首先转换为节点(换句话说,节点(d))之后,我正在 IList> 的列表上尝试该 GroupBy。

所以现在,虽然同样的问题(这里是我的类(class)的更完整的图片给你):

   public class Tree<T> where T : INode
{
private readonly IList<T> _sourceDependencies;
private readonly List<Node<T>> _nodeDependencies;

public Node<T> RootNode { get; set; }
public Dictionary<Node<T>, IList<Node<T>>> FlattenedMap { get; private set; }

public Tree(T rootNode, IList<T> dependencies )
{
RootNode = new Node<T>(rootNode); //convert the custom type to Node<T> first so we can work with it
_sourceDependencies = dependencies;
_nodeDependencies = ConvertListToNodes(_sourceDependencies);

FlattenedMap();
}

private List<Node<T>> ConvertListToNodes(IList<T> listToConvert)
{
List<Node<T>> nodeList = _sourceDependencies.Select(sourceNode => new Node<T>(sourceNode)).ToList();
}


public void CreateFlattenedMap()
{
var parentGroups = _nodeDependencies.GroupBy(d => d.ParentNodeId);

var dictionary = parentGroups.ToDictionary(d => new Node<T>(d), d => d.ToList());

FlattenedMap = dictionary;
}

最佳答案

这会如你所愿吗?

var dictionary = parentGroups.ToDictionary(
d => new Node<T>(d.Key),
d => d.ToList());

关于c# - Convert To Dictionary 需要有一个 Node<T> 作为键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15736901/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com