Conditional Linq Select on nested object

Considering I have a simple object like this

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
                        }
                    }
                }
            };

      

I am trying Select

property description

on TestA

, but if TestB

there is a value TestAId == FkTestAId

in then I want to select TestB

Description

+3


source to share


1 answer


You can use overload DefaultIfEmpty

to use a.Decription

if there is no corresponding b.Description

:

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

      

First

here it is safe and will never throw an exception, because I have specified a fallback value for the case when there was no corresponding element in the subquery, so it is FirstOrDefault

not necessary.




Additional requirements mentioned in the comment:

I want it to be the default if the entry does not exist or Description

in TestB

equal null

or empty

Then you need to change the inner one Where

:

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

      

+7


source







All Articles