在具有lambda的课程列表中查找课程列表

时间:2018-06-25 13:50:37

标签: c# lambda

我有一堂课同步

internal sealed class Synchronize
{
    internal _File File { get; set; } = new _File();
    internal _Log Log { get; set; } = new _Log();

    internal sealed class _File
    {
        internal string Folder { get; set; }
        internal string Name { get; set; }
        internal string Extention { get; set; }
        internal string Create_Date_Time { get; set; }
        internal long Size { get; set; }
        internal int RecordCount { get; set; }
    }

    internal sealed class _Log
    {
        internal string Folder { get; set; }
        internal string Name { get; set; }
        internal string Extention { get; set; }
        internal string CreateDateTime { get; set; }
    }
}

我还有另一个班级迁移

internal sealed class Migrate
{
    internal string FileFolder { get; set; }
    internal string FileName { get; set; }
    internal int RecordCount { get; set; }
    internal bool CanMigrate { get; set; } = false;
}

我有

List<Synchronize> synchronize

List<Migrate> migrate

同步具有100多个列表项,而迁移具有1多个列表项。

有没有一种方法可以使用lambda表达式通过搜索migration.FileFolder && migration.FileName && migration.RecordCount来查找同步存在于迁移中的所有项目?

我知道如何通过遍历迁移的方式对同步进行lambda搜索,但是我试图避免迭代并尝试学习更多的lambda,当您开始掌握它时,它是如此酷:)

3 个答案:

答案 0 :(得分:1)

可以使用

var results = synchronize.Where(s => migrate.Any(m => /* compare here */));

但是我可能会使用联接:

var results = from s in synchronize
              join m in migrate
              on new { s.File.Folder, s.File.Name, s.File.RecordCount }
              equals new { Folder = m.FileFolder, Name = m.FileName, m.RecordCount }
              select s;

或使用lambda语法:

var results = synchronize.Join(migrate,
    s => new { s.File.Folder, s.File.Name, s.File.RecordCount },
    m => new { Folder = m.FileFolder, Name = m.FileName, m.RecordCount },
    (m, s) => s);

答案 1 :(得分:0)

您可以结合使用WhereFirstOrDefault来做到这一点:

var result = synchronize.Where(s => migrate.FirstOrDefault(m => m.FileFolder == s.File.Folder && m.FileName == s.File.Name && m.RecordCount == s.File.RecordCount) != null);

或使用Any

var result = synchronize.Where(s => migrate.Any(m => m.FileFolder == s.File.Folder && m.FileName == s.File.Name && m.RecordCount == s.File.RecordCount));

答案 2 :(得分:0)

是的,可以使用以下方法完成:

var synchronize = new List<Synchronize>();
//fill synchronize    
var migrate = new List<Migrate>();
//fill migrate

var result = synchronize
    .Where(s => migrate.Exists(m => m.FileFolder == s.File?.Folder
                                    && m.FileName == s.File?.Name
                                    && m.RecordCount == s.File?.RecordCount)
    .ToList();

正如DavidG在评论中提到的,最好对任何Enumerable使用扩展方法Any
Exists仅适用于List

result = synchronize
    .Where(s => migrate.Any(m => m.FileFolder == s.File?.Folder
                                    && m.FileName == s.File?.Name
                                    && m.RecordCount == s.File?.RecordCount))
    .ToList();