从两个linq列表中投影到新类



我有一个现有的类,向下配对,看起来像这样:

public class SiloNode
{
public string Key { get; set; }
public List<string> RelatedTopics { get; set; }
public string Url { get; set; }
}

Key是唯一的密钥,而RelatedTopics包含相关密钥的列表。

我维护了这些节点的列表:

List<SiloNode> MasterList = new List<SiloNode>();

我使用一个查询来提取所有相关的主题,然后稍后创建一些链接:

public static IEnumerable<SiloNode> RelatedNodes(this SiloNode root)
{
return MasterList.Where(x => root.RelatedTopics.Contains(x.Key));
}

以上所有工作

但是,我需要更改RelatedTopics,以便添加一些关系特有的锚文本。

因此,首先,我又创建了两个类:

public class RelatedNode
{
public string AnchorText { get; set; }
public string Key { get; set; }
}
public class NodeLink
{
public NodeLink(string url, string text)
{
Url = url;
Text = text;
}
public string Text { get; set; }
public string Url { get; set; }
}

然后我对我的SiloNode类进行更改:

public class SiloNode
{
public string Key { get; set; }
public List<RelatedNode> RelatedTopics { get; set; }
public string Url { get; set; }
}

因此,现在,与其RelatedTopics只包含一个简单的键,它还包含一些我想应用于该关系的锚文本。

这是我正在挣扎的地方-下面的代码不完整

public static IEnumerable<NodeLink> RelatedNodes(this SiloNode root)
{
return MasterList.Where(x => root.RelatedTopics.Contains(x.Key))
.Select(y => new NodeLink(y.Url, "HOW DO I GET ANCHOR TEXT?"));
}

我需要将双方链接在一起,这样我就可以访问y.Url和root。相关主题。文本。

我仍然需要匹配相关的节点,但然后投影到一个新的NodeLink。虽然键在"x"中可用,但锚文本在根目录中。相关主题。我认为当前的linq结构不足以解决这个查询,但我不是专家。

感谢您的帮助。

Any替换Contains,并添加内部Select:

masterList
.Where(m => m.RelatedTopics.Any(t => m.Key == t.Key))
.Select(m => m.RelatedTopics.Where(m.Key == t.Key)
.Select(t => new NodeLink(m.Url, t.AnchorText)));

或者,执行以下操作:

masterList
.Select(m => m.RelatedTopics
.Where(t => m.Key == t.Key)
.Select(t => new NodeLink(m.Url, t.AnchorText)));

最新更新