条件Linq在嵌套对象上选择

时间:2017-07-20 07:52:06

标签: 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
                        }
                    }
                }
            };

我正在尝试Select description TestA TestB属性,但如果TestAId == FkTestAId中的值TestB我要选择<!DOCTYPE html> <html> <head> <title>My First Website</title> <meta charset="UTF-8"/> <!-- Any required CSS or JS files goes here --> </head> <body> <!-- Page content goes here --> </body> </html> df.select(columnName).cast(DataTypes.ErrorType), where df =Dataset<Row> columnname= Name of a String column in the dataset. 说明

1 个答案:

答案 0 :(得分:7)

如果没有匹配的DefaultIfEmpty,您可以使用a.Decription重叠来使用b.Description

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

First在这里是安全的,永远不会抛出异常,因为我已经为&#34;子查询&#34;中没有匹配项的情况指定了回退值,所以{{1}是不必要的。

评论中提到的其他要求:

  

如果记录不存在或FirstOrDefault我想要它默认   Description中的TestB或空

然后你需要修改内部null

Where