fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. public class Test
  6. {
  7. public class GrandParent{
  8. public List<Parent> parentList{ get; set; }
  9. public string name{ get; set; }
  10. public GrandParent(string name){
  11. this.name = name;
  12. this.parentList = new List<Parent>();
  13. }
  14. }
  15. public class Parent{
  16. public List<Child> childList{ get; set;}
  17. public string name{ get; set; }
  18. public Parent(string name){
  19. this.name = name;
  20. this.childList = new List<Child>();
  21. }
  22. }
  23. public class Child{
  24. public string city{ get; set;}
  25. public Child(string city){
  26. this.city = city;
  27. }
  28. }
  29. public static void Main()
  30. {
  31. Child c1 = new Child("ABC"), c2 = new Child("123"), c3 = new Child("tmp");
  32. Parent p1 = new Parent("p1"), p2 = new Parent("p2"), p3 = new Parent("p3");
  33. GrandParent g1 = new GrandParent("g1"), g2 = new GrandParent("g2"), g3 = new GrandParent("g3");
  34.  
  35. p1.childList.Add(c1); p1.childList.Add(c2);
  36. p2.childList.Add(c2);
  37. p3.childList.Add(c3);
  38.  
  39. g1.parentList.Add(p1); g1.parentList.Add(p2); g1.parentList.Add(p3);
  40. g2.parentList.Add(p2);
  41. g3.parentList.Add(p3);
  42.  
  43. List<GrandParent> repo = new List<GrandParent>{g1, g2, g3};
  44.  
  45. var filteredParents = from g in repo
  46. from p in g.parentList
  47. where p.childList.Any(c => c.city == "tmp")
  48. select new Parent(p.name){
  49. childList = p.childList.Where(c => c.city == "tmp").ToList()
  50. };
  51.  
  52. var filteredGrandParents = from g in repo
  53. from p in g.parentList
  54. where filteredParents.Any(fp => fp.name == p.name)
  55. select new GrandParent(g.name){
  56. parentList = g.parentList.Where(pp => filteredParents.Any(fp => fp.name == pp.name)).ToList()
  57. };
  58.  
  59. foreach(var g in filteredGrandParents){
  60. Console.WriteLine(g.name);
  61. foreach(var p in g.parentList){
  62. Console.WriteLine("\t" + p.name);
  63. foreach(var c in p.childList){
  64. Console.WriteLine("\t\t" + c.city);
  65. }
  66. }
  67. Console.WriteLine();
  68. }
  69. }
  70. }
Success #stdin #stdout 0.01s 131520KB
stdin
Standard input is empty
stdout
g1
	p3
		tmp

g3
	p3
		tmp