Search code examples
c#linq

c# Getting object elements with the same values that using linq


I have two objects named LastFiles and DbObj. When I pull the data, I have 2 object lists consisting of these. I created a scenario like this.

public class LastFiles
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public string Translator { get; set; }
    public string Supervisor { get; set; }
    public string Type { get; set; }
    public string FileName { get; set; }
    public string ModifiedDate { get; set; }
}

public class DbObj
{
    public int Id { get; set; }
    public int WorkId { get; set; }
    public string Type { get; set; }
    public int TypeId { get; set; }
}

var lastFiles = new List<LastFiles> {
    new LastFiles { Id = 1, Title = "Title 1", Author = "Author 1", Type = "book", FileName = "file-name-1.pdf" },
    new LastFiles { Id = 2, Title = "Title 2", Author = "Author 2", Type = "book", FileName = "file-name-2.pdf" },
    new LastFiles { Id = 3, Title = "Title 3", Author = "Author 3", Type = "article", FileName = "file-name-3.pdf" },
    new LastFiles { Id = 4, Title = "Title 4", Author = "Author 4", Type = "article", FileName = "file-name-4.pdf" },
    new LastFiles { Id = 5, Title = "Title 5", Author = "Author 5", Supervisor = "Supervisor 1", Type = "thesis", FileName = "file-name-5.pdf" },
    new LastFiles { Id = 6, Title = "Title 6", Author = "Author 6", Supervisor = "Supervisor 2", Type = "thesis", FileName = "file-name-6.pdf" }
};

var dbObj = new List<DbObj> {
    new DbObj { Id = 1, WorkId = 5, Type = "book", TypeId = 1 },
    new DbObj { Id = 2, WorkId = 5, Type = "book", TypeId = 2 },
    new DbObj { Id = 3, WorkId = 5, Type = "thesis", TypeId = 5 },
    new DbObj { Id = 4, WorkId = 5, Type = "thesis", TypeId = 6 },
    new DbObj { Id = 5, WorkId = 278, Type = "article", TypeId = 689 }
};

If I have to go through the scenario; How can I get items from lastFiles that LastFiles.Type value is the same as the DbObj.Type value and the LastFiles.Id is the same as the DbObj.TypeId?


Solution

  • You can use an anonymous object to join two collections like below :

    var result = (from lf in lastFiles
                          join db in dbObj on new { lf.Type, TypeId = lf.Id}
                                       equals new  { db.Type, db.TypeId} 
                          select lf).ToList();
    

    Edit

    Lambda version of the join :

    var result2 = lastFiles.Join(dbObj,lf=> new {lf.Type,TypeId = lf.Id},db=>new  { db.Type,db.TypeId},(lf,db)=> lf  ).ToArray();
    

    Fiddle

    Please note that property names and types should match. You may need renames and casts in actual code.