鉴于我有一个像这样的简单对象
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)
我想Select
在description
财产上TestA
,但如果有一个值TestB
,其中TestAId == FkTestAId
我想选择TestB
说明
如果没有匹配,您可以使用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());
Run Code Online (Sandbox Code Playgroud)
First
这里是安全的,永远不会抛出异常,因为我已经为"子查询"中没有匹配项的情况指定了回退值,所以FirstOrDefault
没有必要.
评论中提到的附加要求:
如果记录不存在或者
Description
输入TestB
是null
空的,我希望它是默认的
然后你需要修改内部Where
:
.Where(b => b.FkTestAId == x.TestAId && !string.IsNullOrEmpty(b.Description))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
565 次 |
最近记录: |