我有A类,B类和C类。
A类为:
public class A
{
public string ColA { get; set; }
}
B类为:
public class B
{
public int ColB { get; set; }
public List<A> a { get; set; }
}
C类为:
public class C
{
public int ColC { get; set; }
public ICollection<B> b { get; set; }
}
我的输入数据是:
var ipData = new[]
{
new { ColC = 1, ColB = 101, ColA = "val1" },
new { ColC = 1, ColB = 101, ColA = "val2" },
new { ColC = 1, ColB = 102, ColA = "val3" },
new { ColC = 1, ColB = 102, ColA = "val4" }
};
我无法在B类列表下列出A类列表。
var objC = new C();
foreach(var data in ipData)
{
objC.ColC = data.ColC;
var objB = new B();
var lstB = new List<B>();
var lstA = new List<A>();
var objA = new A();
objA.ColA = data.ColA;
lstA.Add(objA);
objB = new B { ColB = data.ColB, a = lstA };
lstB.Add(objB);
objC.b = lstB;
}
它将添加第一行数据。但是第二行要为objA
在List<A>
中添加val2
,因为其余数据是相同的。
现在,对于第三行,需要在objB
中添加List<B>
以获得新值102
及其对应的objA
i,e; val3
和val4
。
预期输出为:
Class C
C => 1 , B => 101 , A => val1, val2
B => 102 , A => val3, val4
答案 0 :(得分:1)
您可以使用某些Linq方法(GroupBy和Select)来做到这一点:
List<C> cList2 = ipData.GroupBy(x => x.ColC).Select(colC => new C
{
ColC = colC.Key,
b = colC.GroupBy(colB => colB.ColB).Select(colB => new B
{
ColB = colB.Key,
a = colB.Select(colA => new A
{
ColA = colA.ColA
}).ToList()
}).ToList()
}).ToList();
答案 1 :(得分:0)
我想出了这就是我的输出的原因。
public class Student
{
public string sid { get; set; }
}
public class Strength
{
public int Str { get; set; }
public List<Student> stu { get; set; }
}
public class Profile
{
public int name { get; set; }
public ICollection<Strength> strength { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
var ipData = new[]
{
new { ColC = 1, ColB = 101, ColA = "val1" },
new { ColC = 1, ColB = 101, ColA = "val2" },
new { ColC = 1, ColB = 102, ColA = "val3" },
new { ColC = 1, ColB = 102, ColA = "val4" }
};
var prof = new Profile();
var stren = new List<Strength>();
var dColB = ipData.Select(x => x.ColB).Distinct();
foreach(var newval in dColB)
{
Console.WriteLine(newval);
var colval = ipData.Where(x => x.ColB == newval);
var stud = new List<Student>();
foreach(var nval in colval)
{
var stuval = new Student { sid = nval.ColA };
stud.Add(stuval);
}
var strval = new Strength{ Str = newval, stu = stud };
stren.Add(strval);
}
var dColC = ipData.Select(x => x.ColC).Distinct();
foreach(var data in dColC)
{
prof.name = data;
prof.strength = stren;
}
Console.WriteLine(prof.name);
foreach(var ss in prof.strength)
{
Console.WriteLine(ss.Str);
foreach(var nn in ss.stu)
{
Console.WriteLine(nn.sid);
}
}
}
}