c# - Linq query to consider even records and skip odd record -
below model :
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; } }
below method :
private void mymethod(int testid, int lasttestid) { var list = new list<mydata>();//contains 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++; } } } }
in above method when testid 0 have 2 records in tests , when testid > 0 have 1 record in tests.
now trying find region ids there no subtests(subtest.count=0) test when have 2 test want consider last test , count subtest last test.
my code working fine thing having code duplication want simplify.
instead of loop prefer linq not knowing how linq use loop.
update:
input :
[0] : region = "abc" regionid = 1 "testlist": [ { testid : 100, subtests : //contains records }, { testid : 101, subtests : //contains records }, ], [1] : region = "pqr", regionid = 2 "testlist": [ { testid : 100, subtests : //contains 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 } ]
expected output :
[2,3]
can please me simplify process??
list<mydata> list; ... int[] ids = list.where(x => x.tests.last().subtests.count == 0) .select(x => x.regionid) .toarray();
expression in where
methods can explained "last test in tests collection doesn't have subtests".
after found requiered tests list regionid
select method , save in array.
Comments
Post a Comment