条件Linq在嵌套对象上选择

鉴于我有一个像这样的简单对象

public class TestA { public int TestAId { get; set; } public string Description { get; set; } public IEnumerable TestBCollection { get; set; } } public class TestB { public int TestBId { get; set; } public int FkTestAId { get; set; } public string Description { get; set; } } List a = new List() { new TestA() { TestAId = 1, Description = "Test A Description", TestBCollection = new List() { new TestB() { TestBId = 10, FkTestAId = 1, Description = "Test B Description" // this must be used because of the matching FK } } } }; 

我试图在TestASelect description属性但是如果TestB中有一个值,其中TestAId == FkTestAId我想选择TestB描述

如果没有匹配的b.Description您可以使用DefaultIfEmpty重载来使用b.Description

 var descriptions = a .Select(x => x.TestBCollection .Where(b => b.FkTestAId == x.TestAId) .Select(b => b.Description) .DefaultIfEmpty(x.Description) .First()); 

First是安全的,并且永远不会抛出exception,因为我已经为“子查询”中没有匹配项的情况指定了回退值,因此不需要FirstOrDefault


评论中提到的附加要求:

如果记录不存在或者TestB Descriptionnull或为空,我希望它为默认null

然后你需要修改内部Where

 .Where(b => b.FkTestAId == x.TestAId && !string.IsNullOrEmpty(b.Description))