下面是我的模型: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> SubTests { get; set; }
}
下面是我的方法:
private void MyMethod(int testId, int lastTestId)
{
var list = new List<MyData>();//contains some records
if (testId == 0)
{
var test1 = list[0].Tests[0];
var test2 = list[0].Tests[1];
var regionIds = new List<int>();
int counter = 0;
foreach (var item in list)
{
counter = 0;
foreach (var test in item.Tests)
{
if (test.SubTests.Count != 0 && counter % 2 != 0)
regionIds.Add(item.RegionId);
counter++;
}
}
}
else
{
var test1 = list[0].Tests[0];
var regionIds = new List<int>();
foreach (var item in list)
{
counter = 0;
foreach (var test in item.Tests)
{
if (test.SubTests.Count != 0)
regionIds.Add(item.RegionId);
counter++;
}
}
}
}
在上述方法时testId为0,那么我会在测试中有2条记录,当TestId> 0时,我将在测试中只有1条记录。
现在我试图找到那些没有SubTests(SubTest.Count=0)
的地区ID进行测试,但是当我有2个测试时,我想考虑上次测试并为最后一次测试计数子测试。
我的代码工作正常,但我有一些代码重复,我想简化。
而不是循环我宁愿Linq,但因为我不知道如何用linq做到这一点,所以我使用了for循环。
更新:
输入:
[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]
我怎么能简化这个过程?
举例说明输入和期望输出 – ASh
@ASh:我已经更新了我的问题以包含样本输入和输出 –