C# 考虑记录甚至跳过奇数记录的LINQ查询
以下是我的模型:C# 考虑记录甚至跳过奇数记录的LINQ查询,c#,linq,C#,Linq,以下是我的模型: public class MyData { public int RegionId { get; set; } public string Region { get; set; } public List<Test> Tests { get; set; } } public class Test { public int? TestId { get; set; } public List<SubTest> Sub
public class MyData
{
public int RegionId { get; set; }
public string Region { get; set; }
public List<Test> Tests { get; set; }
}
public class Test
{
public int? TestId { get; set; }
public List<SubTest> SubTests { get; set; }
}
预期输出:
[2,3]
如何简化此过程?Linq的
Select
和Where
方法具有覆盖,其中lambda表达式包含对象及其索引
这是一把小提琴
列表;
...
int[]id=list.Where(x=>x.Tests.Last().SubTests.Count==0)
.选择(x=>x.RegionId)
.ToArray();
中的表达式,其中
方法可以解释为“测试集合中的最后一个测试没有子测试”
在我们从列表中找到所有需要的测试后,我们使用Select方法获得它们的
区域ID
,并保存在数组中。给出输入和预期的示例output@ASh:我已更新我的问题,以包括示例输入和output@Learning,Linq方法Last()
返回序列中的最后一个对象。如果只有一个,那将是最后一个
[0] : Region = "abc"
RegionId = 1
"TestList":
[
{
TestId : 100,
SubTests : //contains some records
},
{
TestId : 101,
SubTests : //contains some records
},
],
[1] : Region = "Pqr",
RegionId = 2
"TestList":
[
{
TestId : 100,
SubTests : //contains some records
},
{
TestId : 101,
SubTests : //No records i.e count = 0
},
],
[2] : Region = "Lmn",
RegionId = 3
"TestList":
[
{
TestId : 100,
SubTests : //No records i.e count = 0
},
{
TestId : 101,
SubTests : //No records i.e count = 0
}
]
[2,3]
list.Where((item,index) => index % 2 == 0)
List<MyData> list;
...
int[] ids = list.Where(x => x.Tests.Last().SubTests.Count == 0)
.Select(x => x.RegionId)
.ToArray();