条件Linq在嵌套对象上选择

R4n*_*c1d 3 c# linq lambda

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

public class TestA
{
    public int TestAId { get; set; }
    public string Description { get; set; }

    public IEnumerable<TestB> TestBCollection { get; set; }
}

public class TestB
{
    public int TestBId { get; set; }
    public int FkTestAId { get; set; }
    public string Description { get; set; }
}

List<TestA> a = new List<TestA>()
            {
                new TestA()
                {
                    TestAId = 1,
                    Description = "Test A Description",
                    TestBCollection = new List<TestB>()
                    {
                        new TestB()
                        {
                            TestBId = 10,
                            FkTestAId = 1,
                            Description = "Test B Description" // this must be used because of the matching FK
                        }
                    }
                }
            };
Run Code Online (Sandbox Code Playgroud)

我想Selectdescription财产上TestA,但如果有一个值TestB,其中TestAId == FkTestAId我想选择TestB说明

Tim*_*ter 7

如果没有匹配,您可以使用DefaultIfEmpty重载:a.Decriptionb.Description

var descriptions = a
    .Select(x => x.TestBCollection
        .Where(b => b.FkTestAId == x.TestAId)
        .Select(b => b.Description)
        .DefaultIfEmpty(x.Description)
        .First());
Run Code Online (Sandbox Code Playgroud)

First这里是安全的,永远不会抛出异常,因为我已经为"子查询"中没有匹配项的情况指定了回退值,所以FirstOrDefault没有必要.


评论中提到的附加要求:

如果记录不存在或者Description 输入TestBnull空的,我希望它是默认的

然后你需要修改内部Where:

.Where(b => b.FkTestAId == x.TestAId && !string.IsNullOrEmpty(b.Description))
Run Code Online (Sandbox Code Playgroud)