【发布时间】:2016-05-17 10:13:29
【问题描述】:
这更像是一个与语言无关的问题,而不是特定于 C# 的问题,但由于它处理命名空间,我想我会将其标记为与 .NET 相关的问题。
假设你有一堆代表命名空间的字符串:
[
"System",
"System.Windows",
"System.Windows.Input",
"System.Windows.Converters",
"System.Windows.Markup",
"System.Windows.Markup.Primitives",
"System.IO",
"System.IO.Packaging"
]
您希望过滤它们,以排除集合中“包含”另一个命名空间的任何命名空间。例如,由于 System 包含 System.Windows,因此将其排除在外。由于System.IO 是System.IO.Packaging 的父级,它同样被排除在外。这种情况一直持续到你最终得到这个:
[
"System.Windows.Input",
"System.Windows.Converters",
"System.Windows.Markup.Primitives",
"System.IO.Packaging"
]
在 C# 中以这种方式过滤列表的有效方法是什么?我正在寻找一种看起来像这样的方法:
public IEnumerable<string> FilterNamespaces(IEnumerable<string> namespaces) {}
任何帮助将不胜感激,谢谢!
编辑:以下是最终对我有用的方法:
public IEnumerable<string> FilterNamespaces(IEnumerable<string> namespaces) =>
namespaces.Where(current => !namespaces.Any(n => n.StartsWith($"{current}.")));
【问题讨论】:
标签: c# .net namespaces