c# – 条件Linq在嵌套对象上选择
发布时间:2020-12-15 23:40:00 所属栏目:百科 来源:网络整理
导读:鉴于我有一个像这样的简单对象 public class TestA{ public int TestAId { get; set; } public string Description { get; set; } public IEnumerableTestB TestBCollection { get; set; }}public class TestB{ public int TestBId { get; set; } public int
鉴于我有一个像这样的简单对象
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 } } } }; 我试图在TestA上选择description属性,但如果TestB中有一个值,其中TestAId == FkTestAId我想选择TestB描述 解决方法
如果没有匹配的b.Description,您可以使用DefaultIfEmpty重载来使用a.Decription:
var descriptions = a .Select(x => x.TestBCollection .Where(b => b.FkTestAId == x.TestAId) .Select(b => b.Description) .DefaultIfEmpty(x.Description) .First()); 首先是安全的,并且永远不会抛出异常,因为我已经为“子查询”中没有匹配项的情况指定了回退值,因此FirstOrDefault是不必要的. 评论中提到的附加要求:
然后你需要修改内部Where: .Where(b => b.FkTestAId == x.TestAId && !string.IsNullOrEmpty(b.Description)) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |