c# - Linq 从嵌套元素加入和投影

标签 c# linq

考虑这个现有的 linq 语句:

IEnumerable<string> queries = LandingSilo.Relationships
    .Where(x => x.Type == 1 && x.RootKey == root.Key)
    .Join(
        nodes,
        r => r.NodeKey,
        n => n.Key,
        (r, n) => n.Queries.SingleOrDefault(q => q.Seq == r.QueryId))
    .Where(q => q != null)
    .Select(q => q.Query);

这个查询并没有完成我需要它做的事情。它只公开来自“n.Queries”的变量,而我需要从“n”本身访问另一个变量,在树的更上层。

必需:n.Urlq.Query - 输出为 KeyValuePair<string,string> .

如您所见,查询链接了两个列表 - LandingSilo.Relationships 和一个由变量 nodes 表示的列表。

Nodes 也有一个嵌套列表属性,其中包含将列表连接在一起所需的键之一,这里是键:

  • LandingSilo.Relationships:NodeKey、QueryId
  • nodes: Key, Queries.Seq (Queries是nodes里面的列表)

规范如下:

LandingSilo.Relationships:List<SiloRelationship>();

public class SiloRelationship
{
    public SiloRelationship(int type, string rootKey, string nodeKey, int queryId)
    {
        Type = type;
        RootKey = rootKey;
        NodeKey = nodeKey; // Key 1
        QueryId = queryId;  // Key 2
    }

    public int Type { get; set; }
    public string RootKey { get; set; }
    public string NodeKey { get; set; }
    public int QueryId { get; set; }
}

节点:List<SiloNode>();

public class SiloNode
{
    public string Key { get; private set; } // Key 1
    public string Url { get; private set; }
    public List<NodeQuery> Queries { get; private set; }
}

public class NodeQuery
{
    public string Query { get; private set; }
    public int Seq { get; private set; } // Key 2
}    

最佳答案

应该能够选择作为 KeyValuePair 连接结果的值

IEnumerable<string> queries = LandingSilo.Relationships
.Where(x => x.Type == 1 && x.RootKey == root.Key)
.Join(
    nodes,
    r => r.NodeKey,
    n => n.Key,
    (r, n) => new KeyValuePair<string,string>(n.Url, n.Queries.SingleOrDefault(q => q.Seq == r.QueryId)?.Query))
.Where(q => q.Value != null);

关于c# - Linq 从嵌套元素加入和投影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51945337/

相关文章:

c# - xslt V1.0 - 具有递归循环的子模板返回空值

c# - 为什么在与 null 类型之间映射时 null 不会导致 NullReferenceException?

c# - 使用 LINQ 和 C# 的随机数组

c# - Caliburn.Micro MVVM WPF - 在用户编辑 DataGrid 时启用按钮,否则禁用它

.net - 如何使用Lambda将LINQ理解查询语法转换为方法语法

c# - 如何使用 linq 和 lambdas 从集合中获得前三名玩家和他们的高分

c# - SET SHOWPLAN_ALL 它来自哪里?

c# - 在post请求中发送文件+参数

c# - guest 帐户限制

c# - c# 中的时间跨度交集