[英]Join two lists and select nested items with linq
I have a list of the following class: 我有以下课程的清单:
public class SiloRelationship
{
public int RelationshipType { get; set; }
public string MasterKey { get; set; }
public string SlaveKey { get; set; }
public int QueryId { get; set; }
}
I have a second list of the following class: 我有以下课程的第二个列表:
public class SiloNode
{
public string Key { get; private set; }
public string Url { get; private set; }
public List<NodeQuery> Queries { get; private set; }
}
Which has a sub-class: 其中有一个子类:
public class NodeQuery
{
public string Query { get; private set; }
public int Seq { get; private set; }
}
Lists: 清单:
Here's my query - there is a simple join, after which I need to return the Url and Query properties - the filter should result in a single QueryNode from the list. 这是我的查询-有一个简单的联接,此后我需要返回Url和Query属性-过滤器应从列表中生成单个QueryNode。
What we have is: 我们拥有的是:
SiloRelationship => 1 to 1 SiloNode => 1 to many QueryNode
A Kvp would be adequate for the purpose of the exercise but I can't see the Query property with the code I've got so far. Kvp足以满足本练习的目的,但是我看不到带有到目前为止的代码的Query属性。
var query =
from r in LandingSilo.Relationships
join n in LandingSilo.Nodes on r.SlaveKey equals n.Key
where r.RelationshipType == 1 &&
n.Queries.Select(y => y.Seq).Contains(r.QueryId)
Any help appreciated. 任何帮助表示赞赏。
You just need to filter the Queries
. 您只需要过滤Queries
。 Change last statement like below 更改最后一条语句,如下所示
select n.Queries.FirstOrDefault(q => q.Seq == q.QueryId);
Try this: 尝试这个:
IEnumerable<string> queries = LandingSilo.Relationships
.Where(r => r.RelationshipType == 1)
.Join(
LandingSilo.Nodes,
r => r.SlaveKey,
n => n.Key,
(r, n) => n.Queries.SingleOrDefault(q => q.Seq == r.QueryId))
.Where(q => q != null)
.Select(q => q.Query);
Line by line: filter all Relationship
s with type different from 1
, join on SlaveKey
/ Key
and select the only query in the node that has the Seq
equal to the Relationship
s QueryId
. 逐行:过滤所有类型不同于1
Relationship
,加入SlaveKey
/ Key
并选择节点中唯一Seq
等于Relationship
的QueryId
。 Filter out null
results and select the Query
property. 筛选出null
结果并选择Query
属性。 This is going to throw an InvalidOperationException
if there are multiple queries within one node matching. 如果一个节点内有多个查询匹配,这将引发InvalidOperationException
。
This can be also done in the LINQ keyword syntax like this: 也可以使用LINQ关键字语法来完成,如下所示:
IEnumerable<string> queries =
from r in LandingSilo.Relationships
where r.RelationshipType == 1
join n in LandingSilo.Nodes on r.SlaveKey equals n.Key
from q in n.Queries.SingleOrDefault(q => q.Seq == r.QueryId)
where q != null
select q.Query;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.