简而言之......
我有一个源控制文件夹列表,它们使用TFS API从变更集中收集结构:
$ / ProjectFolder / BranchName / Project A
$ / ProjectFolder / BranchName / Subfolder / Project B
$ / ProjectFolder / BranchName / Project C
以上只会包含少数项目,然后我会以以下格式列出所有项目名称:
项目A
项目B
项目C
项目D
我正在尝试选择一个在两个列表之间具有连接的新列表,然后获得包含第一个结构和第二个结构的匿名类型。我想我应该使用类似Contains
的内容,但是在尝试使用连接时语法只提供equals
。
我试过了:
var sourceFolders = new List<string>()
{
"$/ProjectFolder/BranchName/Project A",
"$/ProjectFolder/BranchName/Sub-Folder/Project B",
"$/ProjectFolder/BranchName/Project C"
};
var projectNames = new List<string>() { "Project A", "Project B", "Project C", "Project D"};
var filteredProjects = sourceFolders.Where(sourceFolder => projectNames.Any(x => sourceFolder.Contains(x)));
filteredProjects
只会包含sourceFolders
,而不会包含project
映射的内容......
有什么想法吗?
所需的输出
new { SourceFolder = "$/ProjectFolder/BranchName/Project A", ProjectName = "Project A" };
new { SourceFolder = "$/ProjectFolder/BranchName/Subfolder/Project B", ProjectName = "Project B" };
new { SourceFolder = "$/ProjectFolder/BranchName/Project C", ProjectName = "Project C" };
答案 0 :(得分:2)
或者你可以这样做:
var filteredProjects = from source in sourceFolders
let project = projectNames.FirstOrDefault(p => source.Contains(p))
where project != null
select new {
SourceFolder = source,
Project = project
};
答案 1 :(得分:1)
你可能想要这样的东西:
var filteredProjects = sourceFolders
.Select(sf => new {
Project = projectNames.FirstOrDefault(x => sf.Contains(x)),
Folder = sf
})
.Where(o => o.Project != null);
这会将每个源文件夹投影到具有Project
和Folder
属性的匿名类型的实例中;后者是源文件夹,前者是项目的名称(如果null
与特定文件夹不匹配,则可能为projectNames
。)
然后过滤结果以消除与无法与项目关联的文件夹对应的对象。
还有Tuple
- 等效的
var filteredProjects = sourceFolders
.Select(sf => Tuple.Create(
sf, projectNames.FirstOrDefault(x => sf.Contains(x))
))
.Where(t => t.Item2 != null);