我有两个名为 LastFiles
和 DbObj
的对象。当我提取数据时,我有 2 个由这些组成的对象列表。我创建了一个这样的场景。
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 }
};
如果我必须经历这个场景;如何从 lastFiles
获取 LastFiles.Type
值与 DbObj.Type
值和 LastFiles.Id 相同的项目
与 DbObj.TypeId
相同吗?
最佳答案
您可以使用匿名对象来连接两个集合,如下所示:
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();
编辑
联接的 Lambda 版本:
var result2 = lastFiles.Join(dbObj,lf=> new {lf.Type,TypeId = lf.Id},db=>new { db.Type,db.TypeId},(lf,db)=> lf ).ToArray();
请注意,属性名称和类型应匹配。您可能需要在实际代码中进行重命名和转换。
关于c# 使用 linq 获取具有相同值的对象元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73775109/