加入两个列表并使用 linq 选择嵌套项目

我有以下课程的列表:


public class SiloRelationship

{

    public int RelationshipType { get; set; }

    public string MasterKey { get; set; }

    public string SlaveKey { get; set; }

    public int QueryId { get; set; }

}

我有以下类的第二个列表:


public class SiloNode

{

    public string Key { get; private set; }

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

}

列表:


LandingSilo.Relationships 是 SiloRelationship 的列表

LandingSilo.Nodes 是 SiloNode 的列表。

这是我的查询 - 有一个简单的连接,之后我需要返回 Url 和 Query 属性 - 过滤器应该从列表中生成一个 QueryNode。


我们拥有的是:


SiloRelationship => 1 to 1 SiloNode => 1 to many QueryNode 

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)

任何帮助表示赞赏。


吃鸡游戏
浏览 190回答 2
2回答

ibeautiful

尝试这个:IEnumerable<string> queries = LandingSilo.Relationships&nbsp; &nbsp; .Where(r => r.RelationshipType == 1)&nbsp; &nbsp; .Join(&nbsp; &nbsp; &nbsp; &nbsp; LandingSilo.Nodes,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; r => r.SlaveKey,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; n => n.Key,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; (r, n) => n.Queries.SingleOrDefault(q => q.Seq == r.QueryId))&nbsp; &nbsp; .Where(q => q != null)&nbsp; &nbsp; .Select(q => q.Query);逐行:过滤所有Relationship类型不同于 的 s 1,加入SlaveKey/Key并选择节点中唯一Seq与Relationships相等的查询QueryId。过滤null结果并选择Query属性。InvalidOperationException如果在一个节点匹配中有多个查询,这将抛出一个。这也可以在 LINQ 关键字语法中完成,如下所示:IEnumerable<string> queries =&nbsp;&nbsp; &nbsp; from r in LandingSilo.Relationships&nbsp; &nbsp; where r.RelationshipType == 1&nbsp; &nbsp; join n in LandingSilo.Nodes on r.SlaveKey equals n.Key&nbsp; &nbsp; from q in n.Queries.SingleOrDefault(q => q.Seq == r.QueryId)&nbsp; &nbsp; where q != null&nbsp; &nbsp; select q.Query;

ITMISS

您只需要过滤Queries.&nbsp;像下面这样更改最后一个语句select&nbsp;n.Queries.FirstOrDefault(q&nbsp;=>&nbsp;q.Seq&nbsp;==&nbsp;q.QueryId);
打开App,查看更多内容
随时随地看视频慕课网APP