请查看所需内容的粗略代码片段。类A是外部类,它有三个类型B的内部列表。
public class A
{
public List<B> var1;
public List<B> var2;
public List<B> var3;
int x;
int y;
}
public class B
{
public string strA;
public string strB;
public string strC;
}
// This is the new class which i want as output
public class C
{
public string strC1;
public string strC2;
public string strC3;
public int x;
public int y;
public bool direction;
}
List<A> ListA = SomeClass.GetData( );
List<B> ListB= new List<B>();
List<C> ListC = new List<C>();
foreach(A myA in ListA)
{
ListB = myA.var1;
foreach(B mydata1 in ListB)
{
C var = new C();
var.strC1 = mydata1.strA;
var.strC2 = mydata1.strB;
var.strC3 = mydata1.strC;
var.x = myA.x;
var.y = myA.y;
var.direction = true; //if input it is true
ListC.Add(var);
}
ListB = myA.var2;
foreach(B mydata1 in ListB)
{
C var = new C();
var.strC1 = mydata1.strA;
var.strC2 = mydata1.strB;
var.strC3 = mydata1.strC;
var.x = myA.x;
var.y = myA.y;
var.direction = true; //if input it is true
ListC.Add(var);
}
ListC = myA.var3;
foreach(B mydata1 in ListB)
{
C var = new C();
var.strC1 = mydata1.strA;
var.strC2 = mydata1.strB;
var.strC3 = mydata1.strC;
var.x = myA.x;
var.y = myA.y;
var.direction = false; //if input it is true
ListC.Add(var);
}
}
var grpList = ListC.GroupBy(p => p.strC);
我的输出是ListC,它由内部类B和外部类A的元素组成,最终输出被分组。
答案 0 :(得分:0)
编辑回答: 对于扁平目标类C
public class C
{
public string strC1;
public string strC2;
public string strC3;
public int x;
public int y;
public bool direction;
}
只需使用SelectMany展平方法并将其合并几次......
var C1 = A1.SelectMany(p => p.var1, (p,q) => new C(){
strC1 = q.strA,
strC2 = q.strB,
strC3 = q.strC,
x = p.x,
y = p.y,
direction = true
}
).Union(
A1.SelectMany(p => p.var2, (p,q) => new C(){
strC1 = q.strA,
strC2 = q.strB,
strC3 = q.strC,
x = p.x,
y = p.y,
direction = true
})
).Union(
A1.SelectMany(p => p.var3, (p,q) => new C(){
strC1 = q.strA,
strC2 = q.strB,
strC3 = q.strC,
x = p.x,
y = p.y,
direction = false
})
).ToList();
edit2:刚刚意识到我重复了3次以上相同的功能。更简洁的写作方式是:
var fn1 = new Func<A, B, C>( (p,q) => new C(){
strC1 = q.strA,
strC2 = q.strB,
strC3 = q.strC,
x = p.x,
y = p.y,
direction = !p.var3.Contains(q)
});
var C1 = A1.SelectMany(p => p.var1, fn1
).Union(
A1.SelectMany(p => p.var2, fn1)
).Union(
A1.SelectMany(p => p.var3, fn1)
).ToList();
edit3 - 来自var3列表的上述示例中的方向现为false
下面有一篇文章解释了SelectMany ...... http://dotnet.dzone.com/news/selectmany-probably-the-most-p