繁体   English   中英

C# LINQ Group By 并在该组上运行方法

[英]C# LINQ Group By and run method on that group

我有一个查询,它正在查看将源文件与目标文件进行比较的方法的结果,并返回自定义对象,其中源文件的属性在任何目标文件中都不同:

var conflictsAndSources = from conflict in FileConflicts
                                      from source in SourceFileObjects
                                      where conflict.Name == source.Name && conflict.PropertyA != source.PropertyA
                                      select new { Conflict = conflict, Source = source };

从这个查询中,我得到了一个集合conflictsAndSources ,我将它输入到以下方法中:

foreach (var conflictAndSource in conflictsAndSources)
                access.FixFileConflict(conflictAndSource.Conflict.FilePath, conflictAndSource.Conflict.Name, conflictAndSource.Source.PropertyA);

该方法有效,但我的 FixFileConflict 方法出现问题。 每次在 foreach 循环中运行此方法时,都必须打开、修改、保存和关闭文件。 问题是同一个文件可能有数百个冲突,因此该文件将被打开和修改数百次。 我显然想找到一种方法来按 FilePath 对这些冲突进行分组并将它们全部传递到方法中。

我被困在那个部分。 到目前为止,我有这个...

            var Groups = conflictsAndSources.GroupBy(x => (x.Conflict.FilePath));

            foreach(var group in Groups)
            {
                da.FixGroupOfFileConflicts(group.Key, the rest of the owl);
            }

我不需要有关FixGroupOfFileConflicts方法的帮助,而是如何将要处理的整个组传递到该方法中。

对于每个文件,都有层,每个层都有几个属性。 在这种方法中,我希望打开我认为将是group.Key的文件,然后该组中的每个项目都有一个.Name和一个PropertyA设置。 我需要将组的每个成员传递到FixGroupOfFileConflicts以便我可以打开文件,然后遍历传入的组以找到每一层并将其 PropertyA 相应地设置为 Source.PropertyA。

这是最简单的方法:

    var Groups = conflictsAndSources.GroupBy(x => x.Conflict.FilePath, x => x.Source);

    foreach(var group in Groups)        
    {
         da.FixGroupOfFileConflicts(group.Key, group);
    }

那么 FixGroupOfFileConflicts 方法签名将是这样的:

FixGroupOfFileConflicts(string conflictFilePath, IEnumerable<source type here> conflictsOfTheFile);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM