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)
....更多的代碼,然後:轉換成字典都需要有一個節點<T>關鍵
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>>
滿足我多麼希望通過屬性的最終結果形成我的字典。
UPDATE
所以我一直試圖做的,但不符合我的僞以下編碼工作是因爲d是T型和字典真正需要的節點爲重點,不d.Key(非T 。重點),我試圖做這樣的事情:
var dictionary = parentGroups.ToDictionary(d => new Node<T>(d), d => d.ToList());
其實現在我想想,該列表需要不List<d>
或IList<d>
但List<Node<T>(d)>
或<Node<d>>
列表(記住,T爲d的一個實例Node期望任何已經實現了INode的實例)。
因此ToDictionary創建了這個:<d.Key, List<d>>
所以你最終得到(<int, List<d>)
這不是我最終字典所期望的。
不知何故,我需要採取d並將其轉換爲節點上在ToDictionary所以我結束了詞典飛> ...希望我指出這個權利,但你可以得到的,我什麼感覺試圖有希望地說。
UPDATE
所以嘗試的東西在不同的我第一次將我_dependencies到所有節點的實例,試圖使這個更容易使用或使之在我CreateFlattenedMap()
母豬現在的工作,我在循環使用原始依賴列表並將它們中的每一個轉換爲節點(換句話說,節點(d))之後,嘗試將該GroupBy放在IList>的列表中。
所以,現在,雖然同樣的問題(這裏是我班爲您提供更加完整的畫面):
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 => d,d => d.ToList());'沒有辦法嗎? – Yuck
不,d不是類型節點,它只是T –
PositiveGuy
如何定義節點? –