ネストされたオブジェクトの個別の可能な値(名前、型)のリストを抽出したいと思います。 次の入れ子コレクションからプロパティ名とそれぞれのタイプのリストを取得するにはどうすればよいですか? C#でLinqネストされた要素の異なる値を取得
データ構造:
Nodes (List<Node>)
- Node1:
-Properties (List<NodeProperty>) getter: Node1.Properties
-Property1:
-Name: "AAA" (string) getter Property1.Name
-Type: "string" (string) getter Property1.Type
例:
MyNodes:
Node1:
Properties
Property1:
Name: "AAA"
Type: "string"
Property2:
Name: "BBB"
Type: "int"
Node2:
Properties
Property1:
Name: "CCC"
Type: "double"
Property2:
Name: "DDD"
Type: "double"
結果、私はLINQのでこれを抽出することができますどのように
List<KeyValuePair<string, string>> result;
// content of result after the Linq magic:
// AAA -> string
// BBB -> int
// CCC -> double
// DDD -> double
? 抽出明確な名前は次のように働いた:
List<string> names = MyNodes.SelectMany(n => n.Properties.Select(np => np.Name)).Distinct().ToList();
// res: [AAA, BBB, CCC, DDD]
が、これは良いスタートですか?
これには1つのLinqクエリソリューションがありますか?
EDIT
最小限のテストクラスとデータ:実際にそれを実行しなければ
public class Node{
public List<NodeProperty> Properties;
}
public class NodeProperty
{
public string Name;
public string Type;
}
var MyNodes = new List<Node>
{
new Node {
Properties = new List<NodeProperty>
{
new NodeProperty {Name = "node1", Type="string"},
new NodeProperty {Name = "node2", Type="int"},
}
},
new Node {
Properties = new List<NodeProperty>
{
new NodeProperty {Name = "node3", Type="string"},
new NodeProperty {Name = "node4", Type="int"},
}
},
new Node {
Properties = new List<NodeProperty>
{
new NodeProperty {Name = "node1", Type="string"},
new NodeProperty {Name = "node2", Type="int"},
}
}
};
あなたは、有効なC#コードとしてデータを提供してもらえ:以下のクラス&初期化がに基づいて
nodes.SelectMany(n => n.Properties.Select(p => new KeyValuePair<string, string>(p.Name, p.Type))).Distinct().ToList();
?コピー&ペーストアンドランすることができます。 – Enigmativity
いくつかのサンプルデータとクラスを追加しました。 – DDan
サンプルコードはおなじみです:)答えに何か間違っていますか? – AndrewP