Linq获得嵌套元素的独特值

时间:2017-02-17 03:08:32

标签: c# linq

我想提取嵌套对象的不同可能值(名称,类型)的列表。 如何从以下嵌套集合中获取属性名称及其各自类型的列表?

C#中的数据结构:

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"

结果

List<KeyValuePair<string, string>> result;

//  content of result after the Linq magic:
//  AAA -> string 
//  BBB -> int
//  CCC -> double
//  DDD -> double

如何使用Linq提取此内容? 提取不同的名称就像这样:

List<string> names = MyNodes.SelectMany(n => n.Properties.Select(np => np.Name)).Distinct().ToList();
// res: [AAA, BBB, CCC, DDD]

这是一个好的开始吗?

是否有单一的Linq查询解决方案?

修改

最小测试类和数据:

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"},
        }
    }
};

1 个答案:

答案 0 :(得分:3)

没有实际运行和调试......这绝对可能,我认为它看起来类似于:

MyNodes.SelectMany(x => x.Nodes.SelectMany(y => y.Properties.Select(z =>new KeyValuePair<string, string>(z.Name, z.Type))).Distinct().ToList();

修改

在LinqPad中进行此操作。我得到的查询是: nodes.SelectMany(n => n.Properties.Select(p => new KeyValuePair<string, string>(p.Name, p.Type))).Distinct().ToList();

基于班级&amp;初始化如下:

public class Node{
    public List<NodeProperty> Properties;
}

public class NodeProperty
{
    public string Name;
    public string Type;
}    
var nodes = 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"},
        }
    },

};