生成项目的阵列由3个不同的“子阵列”
问题描述:
我有一个类的:生成项目的阵列由3个不同的“子阵列”
class All{
A a;
B b;
C c;
}
现在,我得到3个数组:
A[] as;
B[] bs;
C[] cs;
它们中的每一个可以是空的(长度= 0)或null。
我需要创建一个Alls对象列表,其中包含至少有一个元素的数组(我不需要空对象)。
For example:
A[] as={a1, a2};
B[] bs{};
C[] cs{c1, c2};
=> Result: All[] = {
All{a: a1, b:null, c:null},
All{a: a1, b:null, c:c1},
All{a: a1, b:null, c:c2},
All{a: a2, b:null, c:null},
All{a: a2, b:null, c:c1},
All{a: a2, b:null, c:c2}
All{a: null, b:null, c:c1},
All{a: null, b:null, c:c2}
//All{a: null, b:null, c:null} -> This is an empty object and I don't need it
};
怎样才能全部[]?
答
鉴于Alls
这个定义:
class All
{
public A A { get; set; }
public B B { get; set; }
public C C { get; set; }
}
像这样的东西应该工作:
A[] myAs = new [] { new A(), new A(), new A()};
B[] myBs = new B[] {};
C[] myCs = new [] {new C(), new C()};
var combinations = (from a in myAs.Concat(new A[] { null })
from b in myBs.Concat(new B[] { null })
from c in myCs.Concat(new C[] { null })
where (!(a == null && b == null && c == null))
select new All() { A = a, B = b, C = c }).ToArray();
答
使用对象声明:
Object[] All;
您可以将包括您所创建的所有类的任何对象。
+0
我相信你不明白我的问题。全部由A,B和C组成,我想创建包含A,B和C的所有可能性的所有Alls数组。 – Naor 2011-04-25 15:50:07
答
这是你在找什么? (您可能需要打磨,虽然有点)
List<A> awithnull = as.ToList();
List<B> bwithnull = bs.ToList();
List<C> cwithnull = cs.ToList();
awithnull.Add(null);
bwithnull.Add(null);
cwithnull.Add(null);
var result = from ae in awithnull
from be in bwithnull
from ce in cwithnull
where (!(ae==null && be ==null && ce == null))
select new All() {a = ae, b = be, c = ce};
+0
谢谢!如果我可以 - 我会采取你的两个答案。但BrokenGlass是第一个。 +1 – Naor 2011-04-25 17:34:05
这不包括组合中的null吗? – manojlds 2011-04-25 16:36:37
@manojlds:它确实包括最多从a,b,c中任意两个都为空的组合,但不是所有三个都为空。 – BrokenGlass 2011-04-25 16:39:36
看到我的答案。他期待'null'成为组合中要素的一部分。 – manojlds 2011-04-25 16:43:21