条件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 } } } };
我试图在TestA
上Select
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
Description
为null
或为空,我希望它为默认null
然后你需要修改内部Where
:
上述就是C#学习教程:条件Linq在嵌套对象上选择分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
.Where(b => b.FkTestAId == x.TestAId && !string.IsNullOrEmpty(b.Description))
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1029554.html