考虑这个现有的 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.Url 和 q.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/