我正在尝试使用不基于相等但使用EndsWith的左连接对实体执行LINQ查询。它没有按预期工作,我想知道我是否错误地进行了比较。当我将比较作为相等时,它返回结果,但不是我需要的结果,因为我需要使用EndsWith查看结果,因为属性值。
根据我下面的代码,我应该得到一个如下所示的结果对象:
X Y
BBFile1 File1
XDDFile2 <Empty>
File1TTFile3 File3
相反,我只是得到一个错误,指出&#34;对象引用没有设置为对象的实例&#34;。我搜索过的以及我发现的内容主要指的是我需要在“选择”中设置默认值。声明指示在返回NULL结果时要做什么,但我已经这样做了,它似乎不起作用。
这是我的代码:
List<SFTPFilesListItem> SFTPFullNameList = new List<SFTPFilesListItem>();
List<ArchiveFileListItem> ArchiveFilesList = new List<ArchiveFileListItem>();
SFTPFilesListItem file = new SFTPFilesListItem();
file.FullName = "BBFile1";
SFTPFullNameList.Add(file);
SFTPFilesListItem file2 = new SFTPFilesListItem();
file2.FullName = "XDDFile2";
SFTPFullNameList.Add(file2);
SFTPFilesListItem file3 = new SFTPFilesListItem();
file3.FullName = "File1TTFile3";
SFTPFullNameList.Add(file3);
ArchiveFileListItem afile = new ArchiveFileListItem();
afile.ArchiveFileName = "File3";
ArchiveFilesList.Add(afile);
ArchiveFileListItem afile2 = new ArchiveFileListItem();
afile2.ArchiveFileName = "File1";
ArchiveFilesList.Add(afile2);
ArchiveFileListItem afile3 = new ArchiveFileListItem();
afile3.ArchiveFileName = "File4";
ArchiveFilesList.Add(afile3);
var oldfiles = from sftpfile in SFTPFullNameList
from archivefile in ArchiveFilesList
.Where(x => sftpfile.FullName.EndsWith(x.ArchiveFileName))
.DefaultIfEmpty()
select new
{
x = sftpfile.FullName == null ? string.Empty : sftpfile.FullName,
y = archivefile.ArchiveFileName == null ? string.Empty : archivefile.ArchiveFileName
};
}
public class SFTPFilesListItem
{
public string FullName { get; set; }
}
public class ArchiveFileListItem
{
public string ArchiveFileName { get; set; }
}
答案 0 :(得分:0)
你没有“加入”除了相等之外的任何东西:你生成一个外连接,然后使用WHERE条件选择你想要的行(WHERE选择的方式很有趣,而SELECT项目,但就是这样)