【发布时间】:2017-11-01 15:41:09
【问题描述】:
我有Dictionary<string, List<string>> 对象。 Key 代表文件名,Value 是 List<string>,代表文件中某些方法的名称。
我遍历字典并使用Key 从文件中读取数据。然后我试图在这个文件中找到包含来自Values 对象的元素的行:
static void FindInvalidAttributes(Dictionary<string, List<string>> dictionary)
{
//Get the files from my controller dir
List<string> controllers = Directory.GetFiles(controllerPath, "*.cs", SearchOption.AllDirectories).ToList<string>();
//Iterate over my dictionary
foreach (KeyValuePair<string, List<string>> entry in dictionary)
{
//Build the correct file name using the dictionary key
string controller = Path.Combine(ControllerPath, entry.Key + "Controller.cs");
if (File.Exists(controller))
{
//Read the file content and loop over it
string[] lines = File.ReadAllLines(controller);
for (int i = 0; i < lines.Count(); i++)
{
//loop over every element in my dictionary's value (List<string>)
foreach (string method in entry.Value)
{
//If the line in the file contains a dictionary value element
if (lines[i].IndexOf(method) > -1 && lines[i].IndexOf("public") > -1)
{
//Get the previous line containing the attribute
string verb = lines[i - 1];
}
}
}
}
}
}
必须有一种更简洁的方式来实现if (File.Exists(controller)) 语句中的代码。我不想将foreach 嵌套在for 内部,最父级的foreach 内部。
问题:如何使用 LINQ 确定 string 是否包含 List<string> 中的任何元素?
请注意,这两个值不相同;字符串的一部分应该包含整个列表元素。我能够找到大量示例来查找列表元素中的字符串,但这不是我想要做的。
示例:
lines[0] = "public void SomeMethod()";
lines[1] = "public void SomeOtherMethod()";
List<string> myList = new List<string>();
myList.Add("SomeMethod");
myList.Add("AnotherMethod");
使用上面的数据,lines[0] 应该会导致我的FindInvalidAttributes 方法查看上一行,因为该字符串包含myList 中的第一个元素。 lines[1] 应该不导致方法检查上一行,因为 SomeOtherMethod 没有出现在 myList 中。
编辑我很好奇为什么这被否决并标记为“过于宽泛”而被关闭。我提出了一个非常具体的问题,提供了我的代码、示例数据和示例数据的预期输出。
【问题讨论】:
-
你不能对这个任务使用反射吗?
-
方法定义可以分成不同的行,如果程序员决定这样做会破坏你的逻辑。重载的方法也可能把事情搞砸。获取方法属性(相对于类属性)的示例是here;使用反射获取方法列表作为
MethodInfo对象,然后迭代这些对象以获取每个方法的属性。解析.cs文件我敢肯定是个大黄蜂巢。 -
@Quantic 就我的目的而言,我可以保证方法声明在一行上,并且不需要担心重载。在我的所有控制器中定义的每个
public方法都标有 2 个可能属性中的 1 个。一些 JS 文件奇怪地以非常规的方式调用这些方法,并且需要确保这些方法具有正确的属性分配。我会考虑反思,但我更愿意解决“如何确定字符串是否包含集合中的元素”的一般问题,而不是“此方法具有哪些属性”的具体问题。